单向链表


""
单向链表结构特征:
1.单向:只有前到后的方向
2.节点=数据域+引用域
3.self.__head引用第一个有效节点,如果链表为空则引用空
4.第一个节点称之为头节点,最后一个节点称之为尾节点
5.尾节点的引用与指空
"""
class Node(object):
def __init__(self,data):
# 数据域
self.data=data
# 引用域
self.next=None

class SingleLinkList(object):
def __init__(self):
# 头节点
self.__head=None

# is_empty()链表是否为空
def is_empty(self):
return not self.__head

# add(item)链表头部添加元素
def add(self,data):
node=Node(data)
node.next=self.__head
self.__head=node

# length()链表长度
def length(self):
cur=self.__head
count=0
while cur:
count+=1
cur=cur.next
return count

# travel()遍历整个链表
def travel(self):
cur=self.__head
while cur:
print(cur.data,end='-->')
cur=cur.next
print('')

# append(item)链表尾部添加元素
def append(self,data):
cur = self.__head
if not cur:
self.add(data)
else:
while cur.next:
cur = cur.next
else:
cur.next=Node(data)

# insert(index,data)指定位置添加元素
def insert(self,index,data):
if index<=0:
self.add(data)
elif index >= self.length():
self.append(data)
else:
cur=self.__head
# 插入的位置是index, cur=cur.next偏移index-1次
for _ in range(index-1):
cur=cur.next
node=Node(data)
node.next=cur.next
cur.next=node

# remove(item)删除节点
def remove(self,data):
cur=self.__head
if cur.data == data:
self.__head = cur.next
else:
while cur.next:
if cur.next.data==data:
cur.next=cur.next.next
break
cur =cur.next

# search(item)查找节点是否存在
def search(self,data):
cur=self.__head
while cur:
if cur.data==data:
return True
cur = cur.next
return False

if __name__ == '__main__':
s=SingleLinkList()
for i in range(1,11):
s.append(i)
s.travel()
s.remove(10)
s.travel()
s.insert(0,10)
s.insert(-10,0.1)
s.insert(1000,1000)
s.travel()
posted @ 2021-02-07 22:52  涛子17180  阅读(66)  评论(0编辑  收藏  举报