class Node: def __init__(self, i): self.next = None self.id = i class Linklist: def __init__(self): self.head = None self.tail = None self.length = 0 def insert_after(self, node): if self.head == None: self.head = node self.head.tail = None elif self.head.next == None: self.head.next = node self.head.tail = node else: self.getTailNode().next = node self.head.tail = node self.length += 1 def insert_first(self, node): if self.head == None: self.head = node self.current = node self.head.tail = None else: if self.head.tail == None: self.head.tail = node self.head.next = node else: temp = self.head.next self.head.next = node node.next = temp self.length += 1 def display(self): self.current = self.head if self.head: count = 0 while self.current: print('我是第{}个结点: dada={}'.format(count, self.current.id)) self.current = self.current.next count += 1 else: raise IndexError def getTailNode(self): if self.length > 1: return self.head.tail elif self.length == 1: return self.head return None def pop(self): if self.head == None: return -1 elif self.head.next == None: tmp = self.head self.head = None return tmp else: current = self.head while current: if current.next == self.head.tail and self.length > 2: tmp = self.head.tail self.head.tail = current current.next = None return tmp elif self.length == 2: self.head.tail = None self.head.next = None return self.head current = current.next self.length -= 1 def getLength(self): return self.length def find(self, node): current = self.head count = 1 while current.id != node.id: current = current.next if not current.next: return -1 count += 1 print("该节点是第{}个结点".format(count)) return current def delete(self, node): if node.id == self.head.id: if self.length == 1: self.head = None elif self.length ==2: self.head.tail = None self.head = self.head.next self.head.tail = None else: tmp = self.head.next.tail self.head = self.head.next self.head.tail = tmp elif self.head.tail.id == node.id: current = self.head while current.next != self.head.tail: current = current.next current.next = None self.head.tail = current else: current = self.head while hasattr(current.next, 'id') and current.next.id != node.id: current = current.next if current == self.head.tail: return current.next = current.next.next self.length -= 1 def clear(self): self.head = None
python实现双端链表(原创请勿转载)
最新推荐文章于 2023-07-26 00:47:03 发布