1 问题
如何利用python实现单向循环链表简化数学问题?
2 方法
- add方法:向链表头部添加一个节点data
- append方法:向链表尾部添加一个节点,值为data
- remove方法:删除链表中第一个值为data的节点
代码清单 1
class Node: def __init__(self, data, _next=None): self.data = data self.next = _next class SingleCycleLinkList: def __init__(self): self.head = None self._length = 0 def is_empty(self): return self._length == 0 def length(self): return self._length def nodes_list(self): ls = [] if self.is_empty(): return ls else: ls.append(self.head.data) cur = self.head.next while cur != self.head: ls.append(cur.data) cur = cur.next return ls def add(self, data): node = Node(data) if self.is_empty(): self.head = node node.next = node else: node.next = self.head cur = self.head while cur.next != self.head: cur = cur.next cur.next = node self.head = node self._length = 1 def append(self, data): node = Node(data) if self.head != None: cur = self.head while cur.next != self.head: cur = cur.next cur.next = node node.next = self.head else: self.head = node node.next = node self._length = 1 def insert(self, pos, data): if pos <= 0: self.add(data) elif pos >= self._length: self.append(data) else: node = Node(data) cur = self.head n = 0 while n < pos - 1: cur = cur.next n = n 1 node.next = cur.next cur.next = node self._length = 1 def remove(self, data): if self.is_empty(): return -1 else: cur = self.head flag = True prev = None while cur != self.head or flag: flag = False if cur.data == data: if prev == None last_node = self.head while last_node.next != self.head: last_node = last_node last_node.next = self.head.next self.head = self.head.next else: prev.next = cur.next self._length -= 1 return 0 prev = cur cur = cur.next return -1 def modify(self, pos, data if pos < 0 or pos >= self._length: print("位置不正确") else: cur = self.head n = 0 while n < pos: cur = cur.next n = n 1 cur.data = data def search(self, data): if self.is_empty(): return False else: cur = self.head flag = True flag = False if cur.data == data: return True cur = cur.next return False if __name__ == "__main__": l1 = SingleCycleLinkList() print(l1.head, l1.length()) l1.add(1) print(l1.nodes_list()) l1.add(2) print(l1.nodes_list()) print(l1.head.data, l1.head.next.data, l1.head.next.next.data) l1.append(4) print(l1.nodes_list()) l1.insert(1, 7) print(l1.nodes_list()) l1.remove(2) print(l1.nodes_list()) l1.modify(1, 3) print(l1.nodes_list()) print("查找") print(l1.search(3)) |
---|
3 结语
运用单向循环链表可以用来解决约瑟夫环问题,但目前通过python来解决此类问题只能停留在最基本的层面上,要想深入解决此类问题,则要通过后续的学习,了解更多的python知识,从来实现对该类问题的完美解决。