标签:inverse code inf while list new ini return 空间
方法一:双指针法
采用就地反转,不用额外开辟空间
注意:接收链表的head节点,返回当前节点
方法二:递归法
代码如下:
class Node(object): def __init__(self, item, next=None): self.item = item self.next = next def create_linklist_head(li): head = Node(li[0]) for e in li[1:]: node = Node(e) node.next = head head = node return head def create_linklist_tail(li): head = Node(li[0]) tail = head for e in li[1:]: node = Node(e) tail.next = node tail = node return head def print_linklist(lk): while lk: print(lk.item, end=‘,‘) lk = lk.next def inverse_linklist(head): if head == None or head.next == None: return head currNode = head predNode = None while currNode: tmp = currNode.next currNode.next = predNode predNode = currNode currNode = tmp return predNode def recursion_inverse_lk(head): if head == None or head.next == None: return head new_head = recursion_inverse_lk(head.next) head.next.next = head head.next = None return new_head if __name__ == ‘__main__‘: lk = create_linklist_tail([1,2,3,4,5]) print(‘原始:‘) print_linklist(lk) # res = inverse_linklist(lk) res = recursion_inverse_lk(lk) print(‘\n反转:‘) print_linklist(res)
结果展示:
标签:inverse code inf while list new ini return 空间
原文地址:https://www.cnblogs.com/demo-deng/p/14679133.html