class Node(object): """节点类""" def __init__(self, item): #记录节点的内容 self.item = item #记录下一个节点 self.next=None class SingLinkList(object): def __init__(self): #记录头节点 self.__head=None def is_empty(self): """链表是否为空""" # 判断 return self.__head is None def length(self): """链表长度""" # 定义游标变量,从头往后遍历 cur=self.__head count=0 while cur is not None: count+=1 #游标往后移动 cur= cur.next return count def travel(self): """遍历整个链表""" #定义游标变量。从头往后遍历 cur=self.__head while cur is not None: #输出当前节点内容 print(cur.item,end=" ") #游标往后移动 cur=cur.next print() def add(self,item): """链表头部添加元素""" #创建节点对象 node=Node(item) # 新节点指向原来的头节点 node.next=self.__head # 让头节点记录新节点 self.__head=node def append(self,item): """链表尾部添加元素""" #判断链表是否为空 if self.is_empty(): self.add(item) return #1.遍历找到尾节点 #定义游标变量,从头到尾遍历 cur=self.__head while cur.next is not None: # 游标往后移动 cur=cur.next # 当while循环结束,cur指向的是尾节点 # 2. 让尾节点指向新节点 node=Node(item) cur.next=node def insert(self,pos,item): """指定位置添加元素""" # 健壮性 if pos <= 0: self.add(item) elif pos > (self.length()-1): self.append(item) else: # 1. 找到pos前一个位置的节点 cur=self.__head # 定义下标变量 index = 0 while index < (pos-1): # 游标往后移动 index+=1 cur = cur.next # while循环结束,cur指向的就是pos前一个位置的节点 # 2. 插入新节点 node = Node(item) #让新节点指向pos位置的节点 node.next=cur.next # pos前一个位置的节点指向新节点 cur.next=node def remove(self,item): """删除节点""" # 找到要删除的节点的前置节点 cur=self.__head #记录当前游标的前置节点 pre=None while cur is not None: if cur.item==item: # 2 删除当前节点 #如果pre为空,证明要删除的是头节点 if pre is None: self.__head=cur.next else: pre.next=cur.next break pre=cur cur=cur.next def search(self,item): """查找当前节点是否存在""" cur=self.__head while cur is not None: if cur.item==item: return True cur=cur.next return False
单向链表
最新推荐文章于 2020-10-19 15:09:23 发布