#coding=utf-8
class Node(object):
#节点
def __init__(self,elem):
self.next=None
self.elem=elem
class SingleListLink(object):
"""单链表"""
def __init__(self,node=None):
self.head=node
def is_empty(self):
return self.head==None
def lenth(self):
"""链表长度"""
#cur是一个游标,用来移动遍历节点
cur=self.head
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
def add(self,item):
"""链表头部添加元素"""
node=Node(item)
node.next=self.head
self.head=node
def append(self,item):
"""链表尾部添加元素"""
node=Node(item)
cur=self.head
if self.is_empty:
self.head=Node
else:
while cur.next!=None:
cur=cur.next
cur.next=Node
def insert(self,pos,item):
"""在指定位置添加元素"""
#pos 从0开始
if pos<0:
self.add(item)
elif pos>(self.lenth-1):
self.append(item)
else:
node=Node(item)
pre=self.head
count=0
while count<(pos-1):
count+=1
pre=pre.next
node.next=pre.next
pre.next=node
def remove(self,item):
node=Node(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
单链表single_link_list(python)
最新推荐文章于 2022-11-05 01:34:16 发布