2428-于同学

, ,

# 单向循环链表

class Node(object):
"""节点"""

def __init__(self, elem):
self.elem = elem
self.next = None

"""单链表"""

def __init__(self,node=None):
if node:
node.next = node

def is_empty(self):
"""链表是否为空"""

def length(self):
"""链表长度"""
if self.is_empty():
return 0
count = 1
count += 1
cur = cur.next
return count

def travel(self):
"""遍历整个列表"""
if self.is_empty():
return 0
print(cur.elem, end=" ")
cur = cur.next
print(cur.elem)
print("")

"""链表头部添加元素,头插法"""
node = Node(item)
if self.is_empty():
node.next = node
else:
cur = cur.next

def append(self,item):
"""链表尾部添加元素,尾插法"""
node = Node(item)
if self.is_empty():
node.next = node
else:
cur = cur.next
cur.next = node

def insert(self,pos,item):
"""指定位置添加元素
:param item: 指定增加的具体元素
:param pos 从0开始
"""
if pos <= 0:
elif pos > self.length()-1:
self.append(item)
else:
count = 0
while count < pos-1:
pre = pre.next
count += 1
#循环退出后 pre指向pos-1
node = Node(item)
node.next = pre.next
pre.next = node

def remove(self,item):
"""删除节点"""
if self.is_empty():
return
pre = None
if cur.elem == item:
#判断此节点是否是头节点
rear = rear.next
else:
pre.next = cur.next
return
else:
pre = cur
cur = cur.next
if cur.elem == item:
else:
pre.next = cur.next

def search(self,item):
"""查找节点是否存在"""
if self.is_empty():
return False
if cur.elem == item:
return True
else:
cur = cur.next
if cur.elem == item:
return True
return False


if __name__ == "__main__":
# 检测是否为空
print(li.is_empty())
# 查看链表长度
print(li.length())
# 向链表尾部增加元素
li.append(1)
# 向链表头部增加元素
li.append(2)
li.append(4)
li.append(5)
print(li.length())
# 遍历链表
li.travel()
# 向指定位置增加元素
li.insert(3, 9)
li.travel()
# 删除元素
li.remove(9)
li.travel()


True
0
5
3 1 2 4 5

3 1 2 9 4 5

3 1 2 4 5


Vieu3.3主题

Q Q 登 录