-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinked_list.py
118 lines (106 loc) · 3.61 KB
/
linked_list.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
class Node:
#khởi tạo một phần tử(nút) mới
def __init__(self, data):
self.data = data
self.next = None
class linkedList:
#linked list ở đây sẽ chỉ là single linked list
def __init__(self):
#khởi tạo linked list
self.size = 0
self.head = None
def length(self):
#trả về độ dài linked list
return self.size
def isEmpty(self):
#kiểm tra linked list có rỗng không
return self.size == 0
def printList(self):
#in ra linked list
curNode = self.head
if self.size >= 1:
print(curNode.data, end=" ")
while(curNode.next != None):
curNode = curNode.next
print(curNode.data, end=" ")
print()
else:
print("The list is currently empty")
def appendList(self,val):
#thêm một phần tử vào cuối linked list
newNode = Node(val)
curNode = self.head
if self.size == 0:
self.head = newNode
elif self.size == 1:
self.head.next = newNode
else:
while(curNode.next != None):
curNode = curNode.next
curNode.next = newNode
self.size += 1
def removeTail(self):
#loại đi phần tử cuối linked list
curNode = self.head
if self.size == 0:
print("The list is currently empty")
else:
if(self.head.next == None):
self.head = None
else:
while(curNode.next.next != None):
curNode = curNode.next
curNode.next = None
self.size -= 1
def addFirst(self, val):
#thêm một phần tử vào đầu linked list
newNode = Node(val)
if self.size == 0:
self.head = newNode
else:
newNode.next = self.head
self.head = newNode
self.size += 1
def removeHead(self):
#loại bỏ một phần tử ở đầu linked list
if self.size == 0:
print("The list is currently empty")
else:
self.head = self.head.next
self.size -= 1
def insert(self, val, index):
#thêm một phần tử vào vị trí bất kì của linked list
if index > self.size:
print("Index out of range")
else:
if index == 1:
self.addFirst(val)
else:
count = 1
newNode = Node(val)
curNode = self.head
while(count != index-1):
curNode = curNode.next
count += 1
newNode.next = curNode.next
curNode.next = newNode
self.size += 1
def remove(self,index):
#xoá một phần tử ở vị trí bất kì của linked list
count = 1
curNode = self.head
if self.size == 0:
print("The list is currently empty")
else:
if index > self.size:
print("Index out of range")
else:
if index == 1:
self.removeHead()
else:
while(count != index-1):
curNode = curNode.next
count += 1
curNode.next = curNode.next.next
self.size -= 1
#Vẫn có thể còn nhiều phương thức chưa được cho vào nhưng đây là một số cái tôi hiện tại nghĩ ra được