Python/Data Structure & Algorithm in Python
[Python 기초] 연결리스트 (Linked List)
Air’s Big Data
2020. 8. 10. 10:24
#NODE
class Node: #define function called 'Node'
def __init__(self, item) :
self.val = item #save item in 'val' and this node is the head of linked list
self.next = None #'next' means the other node
#ADD
def add(self, item):
cur = self.head
while cur.next is not None: #cur.next is not None so goes next
cur = cur.next
cur.next = Node(item) #since the next is none, generate new node
#PRINT
def printlist(self):
cur = self.head
while cur is not None:
print(cur.val)
cur = cur.next
#REVERSE
def reverse(self):
prev = None #make a variable '(0)prev'
cur = self.head
while cur is not None: #repeat till cur is none
next = cur.next
cur.next = prev #cur.next goes to (0)prev
prev = cur #prev goes to (1)cur
cur = next #cur gose to (2)next
self.head = prev
Reference :