链表问题-----反转
Posted lee-yl
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了链表问题-----反转相关的知识,希望对你有一定的参考价值。
1、题目:反转单链表或双链表
要求:如果链表长度为N,时间复杂度为O(N),额外的空间复杂度为O(1)
反转单链表的思路:
1 → 2 → 3 → 4 → 5
(1)first = head = 1
循环:
temp = head.next 2
head.next = temp.next 1 → 3
temp.next = first 2 →1
first = temp 2 【此时的头结点是2】
代码:
class Node: def __init__(self,value): self.value = value self.next = None def reverseList(head): if not head: return head first = head while head.next: temp = head.next head.next = head.next.next temp.next = first first = temp return first head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = Node(4) head.next.next.next.next = Node(5) reverseList(head)
反转双链表的思路:
只要将每个节点的 next 和 last 互换就可以了。
代码:
class Node: def __init__(self,value): self.value = value self.next = None def reverseList(head): if not head: return head #重点 while head: head.next , head.last = head.last,head.next head = head.last return head head = Node(1) head.last = None head.next = Node(2) head.next.last = head head.next.next = Node(3) head.next.next.last = head.next head.next.next.next = Node(4) head.next.next.next.last = head.next.next head.next.next.next.next = Node(5) head.next.next.next.next.last = head.next.next.next reverseList(head)
以上是关于链表问题-----反转的主要内容,如果未能解决你的问题,请参考以下文章