class Node:
def __init__(self, data):
self.data = data
self.next = None
node = Node(3)
print(node)
print(node.data)
class Node:
def __init__(self, data):
self.data = data
self.next = None
first_node = Node(5)
second_node = Node(12)
first_node.next = second_node
[5]의 next를 [12]로 지정한다.
[5] -> [12]
노드의 숫자가 많아지고 일일이 연결하려면 반복해서 변수를 지정하기 번거롭기 때문에 LinkedList 라는 이름의 클래스를 만든다!
class LinkedList:
def __init__(self, value):
self.head = Node(value)
linked_list = LinkedList(5)
print(linked_list.head.data) # 5
- head
[3] -> [5] -> [6] -> [8]
- head를 따라서 계속 이동
- head를 변경시킬 수 없으니 cur 변수를 이용
- cur = self.head
cur
[3] -> [5] -> [6] -> [8]- cur = cur.next
----->cur
[3] -> [5] -> [6] -> [8]- cur = cur.next
------------->cur
[3] -> [5] -> [6] -> [8]- cur = cur.next
-------------------->cur
[3] -> [5] -> [6] -> [8]- -------------------->cur___cur.next
[3] -> [5] -> [6] -> [8] -> None
class Node:
def __init__(self, value):
self.data = value
self.next = None
class LinkedList:
def __init__(self, value):
self.head = Node(value)
def append(self, value)
cur = self.head
while cur.next is not None:
cur = cur.next
cur.next = Node(data)
def append(self, value)
if self.head is None:
self.head = Node(data)
return
cur = self.head
while cur.next is not None:
cur = cur.next
cur.next = Node(data)
linked_list = LinkedList(3)
linked_list.append(5) # [3] -> [5] 형태로 노드를 연결
linked_list.append(6) # [3] -> [5] -> [6] 형태로 노드를 연결
linked_list.append(8) # [3] -> [5] -> [6] -> [8] 형태로 노드를 연결
def print_all(self, value)
cur = self.head
while cur is not None:
print("cur is ", cur.data)
cur = cur.next
# cur is 3
# cur is 5
# cur is 6
# cur is 8
def get_node(self, index):
cur = self.head
count = 0
while count < index:
cur = cur.next
count += 1
return cur.data
linked_list = LinkedList(5)
linked_list.append(12)
print(linked_list.get_node(0)) # 5
def add_node(self, index, value):
new_node = Node(value)
if index == 0:
new_node.next = self.head
self.head = new_node
return
node = self.get_node(index-1)
next_node = node.next
node.next = new_node
new_node.next = next_node
def delete_node(self, index):
if index == 0:
self.head = self.head.next
return
node = self.get_node(index - 1)
node.next = node.next.next
def delete_node(self, index):
node = self.get_node(index - 1)
del_node = node.next
if index == 0:
self.head = del_node
return
next_node = del_node.next
node.next = next_node