SingleLinkList () 创建一个空链表
is_empty()判断链表是否为空
length()链表长度
travel()遍历整个链表
add(item)链表头部添加元素
append(item)链表尾部添加元素
insert(pos,item)在指定位置添加元素
remove(item)删除节点
search(item)查找节点是否存在
# coding:utf-8
class Node(object):
"""节点"""
def __init__(self,elem):
self.elem = elem
self.next = None
class SingleLinkList(object):
"""单链表"""
def __init__(self,node=None):
self.__head = node
def is_empty(self):
"""链表是否为空"""
return self.__head ==None
def length(self):
"""链表长度"""
# cur 游标,用来移动遍历节点
cur = self.__head
# countj=记录数量
count = 0
while cur != None:
count += 1
cur = cur.next
return count
def travel(self):
"""遍历整个链表"""
cur = self.__head
while cur !=None:
print(cur.elem)
cur = cur.next
print("")
def add(self, item):
"""链表头部添加元素"""
node = Node(item)
if self.is_empty():
self.__head = node
else:
cur = self.__head
while cur.next !=None:
cur = cur.next
cur.next = node
def append(self,item):
"""链表尾部添加元素"""
node = Node(item)
if self.is_empty():
self.__head = node
else:
cur = self.__head
while cur.next !=None:
cur = cur.next
cur.next = node
def insert(self,pos,item):
"""指定位置添加元素"""
if pos <= 0:
self.add(item)
elif pos >(self.length()-1):
self.append(item)
else:
pre = self.__head
count = 0
while count <(pos-1):
count += 1
pre=pre.next
#当循环退出后,pre指向pos-1位置
node = Node(item)
node.next = pre.next
pre.next = node
def remove(self,item):
"""删除节点"""
cur = self.__head
pre = None
while cur != None:
if cur.elem == item:
#先判断此节点是否为头节点
#头节点
if cur == self.__head:
self.__head = cur.next
else:
pre.next = cur.next
break
else:
pre = cur
cur = cur.next
def search(self,item):
"""查找节点是否存在"""
cur = self.__head
while cur != None:
if cur.elem ==item:
return True
else:
cur = cur.next
return False
if __name__=="__main__":
ll=SingleLinkList()
print(ll.is_empty())
print(ll.length())
ll.append(1)
print(ll.is_empty())
print(ll.length())
ll.append(2)
ll.add(8)
ll.travel()
ll.append(3)
ll.append(4)
ll.append(5)
ll.append(6)
ll.append(7)
ll.insert(-1,9)#9 8 1 234567
ll.travel()
ll.insert(3,99)#9 8 1 99 234567
ll.travel()
ll.remove(9)
用法实例