python实现:
class ListNode(object): def __init__(self, val=0, p=None): self.value = val self.next = p def setNext(self, node): self.next = node class LinkedList(object): def __init__(self): self.head = ListNode() self.len = 0 def insertAfter(self, p: ListNode, val): cur = self.head newNode = ListNode(val) while (1): cur = cur.next if cur == p: newNode.setNext(cur.next) cur.next = newNode break if cur.next == None: return False return True def inertToTail(self, val): cur = self.head newNode = ListNode(val) while (1): if cur.next == None: cur.setNext(newNode) return True cur = cur.next # 反转 def reserve(self): pre = self.head.next cur = self.head.next.next pre.next = None while 1: if cur.next == None: self.head.next = cur cur.next = pre break else: tmp = cur.next #保留状态 cur.next = pre pre = cur cur = tmp def __str__(self): cur = self.head s = "%s->" % str(self.head.value) while (1): if cur.next == None: return s else: s += "%s->" % str(cur.next.value) cur = cur.next if __name__ == ‘__main__‘: ll = LinkedList() for i in range(1, 20): ll.inertToTail(i) print(ll) ll.reserve() print(ll)
反转需注意:反转的时候需要提前记录cur(标记当前位置)的位置,防止cur的next改变导致死循环
go实现:
原文:https://www.cnblogs.com/leescre/p/10401861.html