-
Notifications
You must be signed in to change notification settings - Fork 47
/
base.py
165 lines (126 loc) · 3.11 KB
/
base.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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
#!/usr/bin/env python3
"""
This document is created by magic at 2018/8/16
"""
class LinkNode:
"""
doc node
"""
def __init__(self, item, next=None):
self._item = item
self._next = next
@property
def item(self):
return self._item
@item.setter
def item(self, item):
self._item = item
@property
def next(self):
return self._next
@next.setter
def next(self, next):
self._next = next
def test_link_node():
node_one = LinkNode(1)
node_two = LinkNode(2, node_one)
print(node_two.item)
node_two.item = 100
print(node_two.item)
class LinkedList:
def __init__(self, head=None):
if head:
self.head = head
else:
self.head = LinkNode(0)
def add(self, item):
"""
添加node 头部插入的方式
:param item:
:return:
"""
new_node = LinkNode(item)
new_node.next = self.head
self.head = new_node
def add_tail(self, item):
"""
尾部插入的方式
:param item:
:return:
"""
new_node = LinkNode(item)
point = self.head
while point.next:
point = point.next
point.next = new_node
def reverse(self):
"""
反转链表
:return:
"""
if not self.head or not self.head.next:
return self.head
reversed_head = self.head
head = self.head.next
reversed_head.next = None
p = head.next
while head:
head.next = reversed_head
reversed_head = head
head = p
if p:
p = p.next
self.head = reversed_head
def reverse_recursion(self):
"""
递归的方式反转链表
:return:
"""
pass
def remove(self, index):
"""
根据索引删除链表中的元素
:param index:
:return:
"""
point = self.head
for _ in range(index):
point = point.next
point.next = point.next.next
def insert(self, index, item):
point = self.head
for _ in range(index):
point = point.next
new_node = LinkNode(item)
new_node.next = point.next.next
point.next = new_node
def __len__(self):
length = 1
point = self.head
while point.next:
length += 1
point = point.next
return length
def build_link_list():
lined_list = LinkedList()
lined_list.add_tail("magic 1")
lined_list.add_tail("tom 2")
lined_list.add_tail("ju 3")
lined_list.add_tail("mark 4")
lined_list.add_tail("s 5")
lined_list.add_tail(6)
lined_list.add_tail(7)
return lined_list
def test():
link_list = build_link_list()
print(len(link_list))
# link_list.reverse()
# link_list.remove(2)
# link_list.insert(3, "I am insert 3")
head = link_list.head
while head:
print(head.item)
head = head.next
if __name__ == '__main__':
# test_link_node()
test()