1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
|
class Node(object): """单向循环链表的节点""" def __init__(self, elem): self.elem = elem self.next = None
class SingleCycleLinkList(object): """单向循环链表""" def __init__(self, node=None): self.__head = node if node: node.next = node
def is_empty(self): """链表是否为空""" return self.__head is None
def length(self): """链表长度""" if self.is_empty(): return 0 cur = self.__head count = 1 while cur.next != self.__head: count += 1 cur = cur.next return count
def travel(self): """遍历整个链表""" cur = self.__head while cur.next != self.__head: print(cur.elem, end=" ") cur = cur.next print(cur.elem)
def add(self, item): """链表表头添加,头插法""" node = Node(item) if self.is_empty(): self.__head = node node.next = node else: cur = self.__head while cur.next != self.__head: cur = cur.next node.next = self.__head cur.next = node
def append(self, item): """尾插法""" node = Node(item) cur = self.__head if self.__head is None: self.__head = node else: while cur.next != self.__head: cur = cur.next node.next = self.__head cur.next = node
def insert(self, pos, item): """指定位置添加元素 :param pos: 从0开始 :param item: """ if pos <= 0: self.add(item) elif pos > self.length()-1: self.append(item) else: prior = self.__head count = 0 while count < pos-1: prior = prior.next count += 1 node = Node(item) node.next = prior.next prior.next = node
def remove(self, item): """删除结点 :param item:00 """ if self.is_empty(): return False prior = None cur = self.__head while cur.next != self.__head: if cur.elem == item: if cur == self.__head: rear = self.__head while rear.next != self.__head: rear = rear.next self.__head = cur.next rear.next = self.__head else: prior.next = cur.next print("删除%d成功" % item) return else: prior = cur cur = cur.next if cur.elem == item: if cur == self.__head: self.__head is None else: prior.next = cur.next
else: print("没有这个元素,删除失败")
def search(self, item): count = 0 if self.is_empty(): return print("空的,查找%d失败" % item) else: cur = self.__head while cur.next != self.__head: if cur.elem == item: return count else: cur = cur.next count += 1 if cur.elem == item: return True print("查找%d失败,没有这个元素" % item)
if __name__ == '__main__': ll = SingleCycleLinkList() print(ll.is_empty())
print(ll.length()) ll.add(0) ll.append(1) ll.append(2) ll.append(5) ll.append(3) ll.add(20) ll.insert(-1, 9) ll.insert(3, 90) ll.travel() print("\n********************") ll.search(3233) ll.remove(5) ll.travel()
|