单链表是一个变形的单向循环链表,链表中最后的一个节点的next域不再为None,而是指向链表的头结点
单向循环链表的增、删、查实现
class Node(object):
def __init__(self, item):
self.item = item
self.next = None
class SinCyLinkList(object):
def __init__(self):
self.head = None
def is_empty(self):
return self.head == None
def length(self):
'''链表长度'''
if self.is_empty():
return 0
count = 1
cur = self.head
while cur.next != self.head:
count += 1
cur = cur.next
return count
def travel(self):
'''遍历链表'''
if self.is_empty():
return
cur = self.head
while cur.next != self.head:
print(cur.item)
cur = cur.next
def add(self, item):
'''在头部插入节点'''
node = Node(item)
if self.head == None:
self.head = node
node.next = self.head
else:
node.next = self.head
cur = self.head
while cur.next != self.head:
cur = cur.next
cur.next = node
self.head = node
def append(self, item):
'''在尾部插入节点'''
node = Node(item)
if self.head == None:
self.head = node
node.next = self.head
else:
cur = self.head
while cur.next != self.head:
cur = cur.next
cur.next = node
node.next = self.head
def insert(self, pos, item):
'''在指定位置添加节点'''
if pos <= 0:
self.add(item)
elif pos > (self.length()-1):
self.append(item)
else:
node = Node(item)
cur = self.head
count = 0
while count < (pos-1):
count += 1
cur = cur.next
node.next = cur.next
cur.next = node
def remove(self, item):
'''删除一个节点'''
if self.is_empty():
return
cur = self.head
pre = None
#若删除的是头节点
if cur.item == item:
if cur.next != self.head:
#先找到尾节点
while cur.next != self.head:
cur = cur.next
cur.next = self.head.next
self.head = self.head.next
else:
self.head = None
else:
pre = self.head
while cur.next != self.head:
if cur.item == item:
pre.next = cur.next
return
else:
pre = cur
cur = cur.next
if cur.item == item:
pre.next = cur.next
def search(self, item):
if self.is_empty():
return False
cur = self.head
if cur.item == item:
return True
while cur.next != self.head:
cur = cur.next
if cur.item == item:
return True
return False
if __name__ == "__main__":
ll = SinCyLinkList()
print(ll.head)
ll.add(1)
ll.add(2)
ll.add(3)
ll.insert(2, 4)
ll.insert(4,5)
ll.insert(0, 6)
print("length:",ll.length())
print("删除前:")
ll.travel()
print(ll.search(3))
print(ll.search(7))
print("删除节点")
ll.remove(1)
print("遍历链表")
ll.travel()