시작하기무료로 시작하기

연결 리스트의 맨 앞에 노드 삽입하기

이전 연습 문제에서 Node()LinkedList() 클래스를 구현하는 방법을 배웠어요.

이번 연습에서는 연결 리스트의 맨 앞에 새 노드를 추가하는 insert_at_beginning() 메서드를 위한 코드를 준비해 볼 거예요.

Node() 클래스를 다시 살펴보세요:

class Node:
  def __init__(self, data):
    self.data = data
    self.next = None

이 연습은 강의의 일부입니다

Python으로 배우는 자료구조와 알고리즘

강의 보기

연습 안내

  • 새 노드를 생성하세요.
  • 연결 리스트에 head 노드가 있는지 확인하세요.
  • 연결 리스트에 head 노드가 있으면, 새 노드의 nexthead를 가리키도록 하세요.

실습형 인터랙티브 연습

이 예제를 이 샘플 코드를 완성하여 풀어보세요.

def insert_at_beginning(self, data):
    # Create the new node
    new_node = ____(data)
    # Check whether the linked list has a head node
    if self.____:
      # Point the next node of the new node to the head
      new_node.___ = self.____
      self.head = new_node
    else:
      self.tail = new_node      
      self.head = new_node
코드 편집 및 실행