Linked List (2) - Append and Pop
Append
def append(self, value):
new_node = Node(value)
if self.head is None:
self.head = new_node
self.tail = new_node
else:
self.tail.next = new_node
self.tail = new_node
self.length += 1
Explanation of the Code
The append method adds a new node with the given value to the end of the list:
append 메서드는 주어진 값을 가진 새로운 노드를 리스트의 끝에 추가한다.
A new node is created using the
Nodeclass.Node클래스를 사용해 새로운 노드를 생성한다.If the list is empty (
self.headisNone), the new node becomes both theheadand thetail.리스트가 비어 있으면(
self.head는None), 새 노드는head와tail이 된다.If the list is not empty, the
nextpointer of the currenttailis set to the new node, and thetailis updated to this new node.리스트가 비어 있지 않다면, 현재
tail의next포인터를 새 노드로 설정하고,tail을 이 새 노드로 업데이트한다.The length of the list is increased by 1.
리스트의 길이를 1 증가시킨다.
Pop
def pop(self):
if self.length == 0: # If the list is empty, return None
return None
temp = self.head # Set temp to the head node
pre = self.head # Set pre to the head node as well
while(temp.next): # Traverse the list until temp reaches the last node
pre = temp # Move pre to the current temp's position
temp = temp.next # Move temp to the next node
self.tail = pre # Set tail to pre, the second-to-last node
self.tail.next = None # Remove the last node by setting tail's next to None
self.length -= 1 # Decrease the length of the list
if self.length == 0: # If the list is now empty, reset head and tail to None
self.head = None
self.tail = None
return temp # Return the removed node, or use temp.value to return just the value
The pop method in a linked list removes and returns the last node of the list.
링크드 리스트에서 pop 메서드는 리스트의 마지막 노드를 제거하고 반환하는 기능을 한다.
Explanation of the Code
Check if the list is empty
If the list length is 0, it returnsNonebecause there is nothing to pop.
리스트의 길이가 0이면, 더 이상 제거할 노드가 없기 때문에None을 반환한다.Initialize
tempandpre
Bothtempandpreare initially set to theheadnode to start traversing the list.
temp와pre는 모두 리스트의head로 설정되어 리스트를 순회하기 시작한다.Traverse the list
The loop movestempto the next node and updatespreto followtemp. The loop stops whentempreaches the last node.
While 루프 문은temp를 다음 노드로 이동시키고,pre도temp를 따라 이동한다. 루프는temp가 마지막 노드에 도달할 때까지 계속된다.Update
tail
Once the last node is reached,prewill point to the second-to-last node. We settailtopreand remove the last node by settingtail.nexttoNone.
마지막 노드에 도달하면,pre는 끝에서 두 번째 노드를 가리키게 된다.tail을pre로 설정하고,tail.next를None으로 바꿔 마지막 노드를 제거한다.Adjust the list length
The length of the list is decremented by 1.
리스트의 길이를 1 줄인다.Handle the case where the list is empty after popping
If the list is now empty (length is 0), bothheadandtailare reset toNone.
리스트의 길이가 0이 되면,head와tail을None으로 초기화한다.Return the removed node
Finally, the method returns the removed node (temp). If you want to return just the value, you can returntemp.valueinstead.
마지막으로, 제거된 노드(temp)를 반환한다. 값을 반환하려면,temp.value를 이용하면 된다.