class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class SingleLinkList: def __init__(self,node=None): self.__head=node def is_empty(self): '''判断列表是否为空''' return self.__head==None def length(self): '''链表长度''' 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.val,end=' ') cur=cur.next print(' ') def append(self,item): '''在链表尾部添加元素''' node=ListNode(item) if self.is_empty(): self.__head=node else: cur=self.__head while cur.next!=None: cur=cur.next cur.next=node def add(self,item): '''在链表头部添加元素''' node=ListNode(item) node.next=self.__head self.__head=node def insert(self,pos,item): '''在指定位置添加元素 :param pos 索引从0开始 ''' if pos<0: self.add(item) elif pos>=self.length(): self.append(item) else: node=ListNode(item) pre=self.__head count=0 while count<pos-1: pre=pre.next count+=1 node.next=pre.next pre.next=node def search(self,item): '''查找元素 若找到元素返回元素索引 若找不到返回-1 ''' cur=self.__head count=0 while cur!=None: count+=1 if cur.val==item: return count-1 else: cur=cur.next return -1 def remove(self,item): '''删除制定元素病返回删除前元素的索引''' print(self.search(item)) cur=self.__head pre=None while cur!=None: if cur.val==item: if pre==None: self.__head=cur.next else: pre.next=cur.next cur.next=None break else: pre=cur cur=cur.next
标签:node,head,.__,cur,self,next,链表,节点 From: https://www.cnblogs.com/yyyjw/p/18000172