모두CBT

다음은 단순 연결 리스트를 이용하여 스택 자료구조를 구현한 파이썬 코드… | [7급 국가직 자료구조론] 24년 1회차 기출문제 상세 페이지

1[7급 국가직 자료구조론] 24년 1회차
다음은 단순 연결 리스트를 이용하여 스택 자료구조를 구현한 파이썬 코드이다. (가), (나)에 들어갈 내용을 바르게 연결한 것은?
class Node:
def __init__(self, data, next):
self.data=data
self.next=next

class MyStack:
def __init__(self):
self.top=None

def push(self, data):
( (가) )
self.top=n

def pop(self):
if self.top!=None:
n=self.top
( (나) )
return n.data
1
n=Node(data, None) / self.top=n.next.next
2
n=Node(data, None) / self.top=self.top.next
3
n=Node(data, self.top) / self.top=n.next.next
4
n=Node(data, self.top) / self.top=self.top.next
해설

(가)는 n=Node(data, self.top), (나)는 self.top=self.top.next이다.

push는 새 노드의 next가 기존 top을 가리키게 만든 뒤 top을 새 노드로 바꿔야 연결이 유지된다. pop은 꺼낼 노드를 n에 보관하고 top을 바로 아래 노드로 옮긴다.

  • Node(data, None) / self.top=n.next.next 조합은 새 노드가 기존 스택과 끊기고, pop에서 노드 하나를 건너뛴다.
  • Node(data, None) / self.top=self.top.next 조합은 pop은 맞지만 push할 때마다 기존 스택이 연결에서 사라진다.
  • Node(data, self.top) / self.top=n.next.next 조합은 push는 맞지만 n이 top이므로 두 칸 아래로 이동해 원소 하나가 사라진다.

오류나 개정된 내용이 보이면 알려주세요

이어서 풀어보기

[7급 국가직 자료구조론] 24년 1회차 25문항 이어서 보기문제·정답·해설을 한 페이지에서 이어서 볼 수 있어요7급 국가직 자료구조론 기출문제 암기장 전체 보기