-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinked_list_make_LinkedList.py
73 lines (60 loc) · 1.59 KB
/
linked_list_make_LinkedList.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
"""
Linked List 구현
"""
class Node:
def __init__(self, value=0, next=None):
self.value = value
self.next = next
# first = Node(1)
# second = Node(2)
# third = Node(3)
# first.next = second
# second.next = third
# first.value = 6
class LinkedList(object):
def __init__(self):
self.head = None
self.tail = None
def append(self, value):
new_node = Node(value)
if self.head is None:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
def append_tail(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 = self.tail.next
def get(self, idx):
current = self.head
for _ in range(idx):
current = current.next
return current.value
def insert(self, idx, value):
current = self.head
new_node = Node(value)
for _ in range(idx - 1):
current = current.next
new_node.next = current.next
current.next = new_node
def remove(self, idx):
current = self.head
for _ in range(idx - 1):
current = current.next
current.next = current.next.next
ll = LinkedList()
ll.append(1)
ll.append(2)
ll.append(3)
ll.append(4)
ll.insert(2, 9)
print(ll.get(0), ll.get(1), ll.get(2), ll.get(3))
ll.remove(1)
print(ll.get(0), ll.get(1), ll.get(2), ll.get(3))