python数据结构之单链表
单链表的操作
1、is_empty()链表是否为空
2、length()链表的长度
3、add()链表的头部添加元素
4、append()链表尾部添加元素
5、insert()指定位置添加元素
6、remove()删除节点
7、search()查找链表是否存在
源代码
class Node():
"""节点"""
def __init__(self,data = None):
self.elem = data #节点中的数据
self.next = None #下一个地址(元组也可以实现)
class singleLinkedLists(object):
"""单链表的实现"""
#创建头结点
def __init__(self, node = None):
self.__head = node
def isEmpty(self):
"""链表是否为空"""
return self.__head == None
def length(self):
"""链表的长度"""
cur = self.__head
if self.__head == None:
return 0
else:
count = 1
while cur.next != None:
count += 1
cur = cur.next
return count
def travel(self):
"""遍历链表"""
cur = self.__head
if self.__head == None:
return "空链表"
else:
while cur.next != None:
print(cur.elem,end=" ")
cur = cur.next
print(cur.elem)
def append(self, data):
"""链表尾部添加元素(尾插法)"""
node = Node(data)
if self.__head == None:
self.__head = node
else:
cur = self.__head
while cur.next != None:
cur = cur.next
cur.next = node
def insert(self,pos,data): #pos表示插入位置,item表示插入数据
"""指定位置添加元素
:param pos 从1开始
"""
if pos < 1:
self.add(data)
return
elif pos > self.length():
self.append(data)
return
count = 1 #count用来记录位置
cur = self.__head
node = Node(data)
if pos == 1:
node.next = self.__head
self.__head = node
else:
while cur.next != None:
if count == pos - 1:
node.next = cur.next
cur.next = node
break
count += 1
cur = cur.next
def add(self,data):
"""在头部添加元素(头插法)"""
node = Node(data)
if self.__head == None:
self.__head = node
else:
node.next = self.__head
self.__head = node
def remove(self,data):
"""删除节点(删除具体数据,有多个全部删除)"""
cur = self.__head
pre = None
while cur != None:
if cur.elem == data:
#判断是否头结点
if cur == self.__head:
self.__head = cur.next
else:
pre.next = cur.next
pre = cur
cur = cur.next
else:
pre = cur
cur = cur.next
def search(self,data):
"""查找链表是否存在"""
cur = self.__head
while cur != None:
if cur.elem == data:
return "该数据存在于链表中"
else:
cur = cur.next
return "该数据不存在于链表中"
if __name__ == '__main__':
#以下为测试用例
sll = singleLinkedLists()
#print(sll.is_empty())
#print(sll.length())
node = Node(100)
ll = singleLinkedLists()
for i in range(1,10):
ll.append(i)
for j in range(100,109):
ll.add(j)
print(ll.insert(-1,633))
print(ll.remove(9))
print(ll.travel())
print("*************")
print(ll.length())
print(ll.search(693))