python链表操作

python的链表操作

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
class Node():
def __init__(self, value=None, next=None):
self.__value = value
self.__next = next

def getValue(self):
return self.__value

def getNext(self):
return self.__next

def setValue(self, newValue):
self.__value = newValue

def setNext(self, nexNext):
self.__next = nexNext

class Link():
def __init__(self):
self.__head = Node() #头结点,不存放元素,哨兵节点
self.__tail = None
self.__length = 0

def isEmpty(self):
'''
判断链表是否为空
:return:
'''
return self.__head.getNext() == None

def add(self, value):
'''
头插法插入元素
:param value:
:return:
'''
newnode = Node(value, None)
newnode.setNext(self.__head.getNext())
self.__head.setNext(newnode)

def append(self, value):
'''
尾插法插入元素
:param value:
:return:
'''
newnode = Node(value)
if self.isEmpty():
self.__head.setNext(newnode)
else:
current = self.__head.getNext()
while current.getNext() != None:
current = current.getNext()
current.setNext(newnode)

def search(self, value):
'''
查找链表中是否含有该元素
:param value:
:return:
'''
current = self.__head
foundvalue = False
while current != None and not foundvalue:
if current.getValue() == value:
foundvalue = True
else:
current = current.getNext()
return foundvalue

def index(self, value):
'''
查找该元素在链表中的下标位置,
若没有则返回None
:param value:
:return:
'''
current = self._head
count = 0
found = None
while current != None and not found:
count += 1
if current.getValue() == value:
return count
return None

def print(self):
'''
打印链表元素
:return:
'''
current = self.__head.getNext()
while current != None:
print(current.getValue())
current = current.getNext()

def delete(self, value):
'''
删除指定元素
:param value:
:return:
'''
current = self._head
while current.getNext() != None and current.getNext().getValue() != value:
current = current.getNext()
if current.getNext() == None:
return 0 #链表中无此元素,删除失败
else:
r = current.getNext()
current.setNext(r.getNext())
del r
return 1
------ 本文结束 ------
0%