classNode(object):def__init__(self, data):
self.data = data
self.next=None
头插法添加元素
先生成新结点
遍历单链表
classNode(object):def__init__(self, data):
self.data = data
self.next=NoneclassList(object):'''创建一个单链表类'''def__init__(self):'''初始化单链表'''
self.__head =None# 表头,head为空defis_empty(self):if self.__head:return1else:return0defadd(self, item):'''头插法'''
s = Node(item)# 生成新节点
s.next= self.__head
self.__head = s
deftravel(self):'''遍历单恋表'''
p = self.__head # 定义指针p,p从表头开始while p !=None:print(p.data, end='')
p = p.next# 指针移动到下一元素
尾插法
先把指针移动到最后一个节点
创建一个节点
把新结点的地址放在最后一个节点的指针域里
指定位置插入元素insert(self, pos, x)
按值删除元素
单链表增删查改完整代码python
classNode(object):def__init__(self, data):
self.data = data
self.next=NoneclassList(object):'''创建一个单链表类'''def__init__(self):'''初始化单链表'''
self.__head =None# 表头,head为空defis_empty(self):if self.__head:return1else:return0defadd(self, item):'''头插法'''
s = Node(item)# 生成新节点
s.next= self.__head
self.__head = s
defadd(self, item):'''头插法'''
s = Node(item)# 生成新节点
s.next= self.__head
self.__head = s
defadd_end(self, x):'''尾插法'''
s = Node(x)
p = self.__head
if self.__head ==None:
self.__head = s
else:while p.next!=None:
p = p.next
p.next= s
definsert(self, pos, x):'''指定位置插入元素'''
p = self.__head
count =0if pos >= self.length():return-1while count < pos:
p = p.next
count +=1
s = Node(x)
s.next= p.next
p.next= s
return1defremove(self, item):
p = self.__head
if p.data == item:
self.__head = p.nextelse:while p!=Noneand p.data!=item:
pre = p
p = p.next
pre.next= p.nextdeftravel(self):'''遍历单恋表'''
p = self.__head # 定义指针p,p从表头开始while p !=None:print(p.data, end=' ')
p = p.next# 指针移动到下一元素print('\n')deflength(self):
p = self.__head
count =0while p !=None:
count +=1
p = p.nextreturn count
defsearch_pos(self, pos):'''按序号查找,pos是待查找的位置'''
p = self.__head
count =1# 计数器if pos <1:# 判断位置是否合法returnNoneelse:while p !=Noneand count != pos:
p = p.next
count +=1return p # 成功返回节点pdefsearch_value(self, value):'''search a item by value'''
p = self.__head
while p!=Noneand p.data!=value:
p = p.nextif p.data == value:return p
elif p ==None:returnNone