链表问题(3)-----反转
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)
二、题目:反转部分单链表
思路:
简单来说,找到要反转的部分反转,然后将前面部分和后面部分连接起来即可。
代码:
class Node: def __init__(self,value): self.value = value self.next = None def reverseList(head,a,b): if not head: return head n = 0 pre = Node(None) while head: n += 1 pre = head if n == a-1 else pre head = head.next if a > b or b > n or a < 1: return head head ,first = pre.next , pre.next while a < b: tail = head.next.next temp = head.next head.next = tail temp.next = first first = temp a += 1 if pre: pre.next = first return pre 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) a = 2 b = 4 reverseList(head,a,b)
三、将单链表的每k个节点之间逆序
法一:时间O(N),空间O(K)。利用栈结构存k个数
法二:时间O(N),空间O(1)