#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 :
'Python > Data Structure & Algorithm in Python' 카테고리의 다른 글
[Python 자료구조] 연결리스트 (Linked List) (0) | 2020.09.09 |
---|---|
[Algorithm] 동적계획법(Dynamic programming) - Brute Force, Kadane’s Algorithm (0) | 2020.09.06 |
[Python 기초] 재귀 알고리즘 (recursive algorithms) (0) | 2020.09.06 |
[Python 기초] 탐색 (search) (0) | 2020.09.06 |
[Python 기초] 정렬 (sort) (0) | 2020.09.05 |
댓글