- 노드는 데이터를 담을 수 있는 변수와 다음 주소를 가리키는 변수 총 두개가 존재한다.
노드가 하나만 존재한다면 다음을 가리키는 주소값은 NULL을 가리키게 된다.
class Node:
def __init__(self, item):
self.val = item
self.next = None
마지막 노드일때 next가 가리키고 있는 값은 NULL이라는 점을 이용해 노드를 추가해주었습니다.
def add(self, item):
cur = self.head
while cur.next is not None:
cur = cur.next
cur.next = Node(item)
def remove(self, item):
if self.head.val == item:
self.head = self.head.next
else:
cur = self.head
while cur.next is not None:
if cur.val == item:
self.removeItem(item)
return
cur = cur.next
def removeItem(self, item):
cur = self.head
while cur.next is not None:
if cur.next.val == item:
nextnode = cur.next.next
cur.next = nextnode
break
def reverse(self):
prev = None
cur = self.head
while cur is not None:
next = cur.next
cur.next = prev
prev = cur
cur = next
self.head = prev