class Node(object):
def __init__(self,item):
self.elem = item
self.next = None
class Sing_rec_link(object):
def __init__(self,node=None):
self.head = node
if node:
node.next = node
def is_empty(self):
return self.head == None
def length(self):
cur = self.head
count = 1
if self.is_empty():
return 0
else:
#循环终止条件要注意
while cur.next != self.head:
count+=1
cur = cur.next
return count
def travel(self):
#遍历
if self.is_empty():
raise Exception('Linklist is empty!!!!')
else:
cur = self.head
while cur.next != self.head:
print(cur.elem,end=' ')
cur = cur.next
print(cur.elem,end=' ')
print('')
def add(self,item):
#头插法
node = Node(item)
if self.is_empty():
self.head = node
node.next = node
else:
cur = self.head
while cur.next != self.head:
cur = cur.next
node.next = self.head
self.head = node
cur.next = node
def append(self,item):
node = Node(item)
if self.is_empty():
self.head = node
node.next = node
return
cur = self.head
while cur.next != self.head:
cur = cur.next
cur.next = node
node.next = self.head
def insert(self,pos,item):
node = Node(item)
cur = self.head
curpos = 0
pre = None
if pos <= 0:
self.add(item)
elif pos >= self.length():
self.append(item)
else:
while curpos != pos:
curpos+=1
pre = cur
cur = cur.next
pre.next = node
node.next = cur
def Search(self,item):
if self.is_empty():
return False
cur = self.head
while cur.next != self.head:
if cur.elem == item:
return True
else:
cur = cur.next
if cur.elem == item:
return True
return False
def remove(self,item):
if self.is_empty():
raise Exception('empty!!')
cur = self.head
pre = None
find = False
while cur.next != self.head:
if cur.elem == item:
if cur == self.head:
rear = self.head
while rear.next != self.head:
rear = rear.next
self.head = cur.next
rear.next = self.head
else:
pre.next = cur.next
find = True
break
else:
pre = cur
cur = cur.next
if not find:
if cur.elem == item:
if cur == self.head:
self.head = None
return
pre.next = self.head
需要注意的是。条件 cur.next != self.head
特殊情况1):空链表
2)头结点操作
3)尾节点操作
4)只有一个节点的操作