Leetcode25[Hard] 链表反转-递归
思路借鉴:递归必看,下面是 代码
.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode curr = head;
int count = 0;
while (curr != null && count != k) { // find the k+1 node
curr = curr.next;
count++;
}
if (count == k) { // if k+1 node is found
curr = reverseKGroup(curr, k); // reverse list with k+1 node as head
while (count-- > 0) { // reverse current k-group:
// keep adding new node to the head of finished part.
ListNode next = head.next; // next - next head in upgoing part
head.next = curr; // concatenate head to finished part
curr = head; // update the head of finished part
head = next; // update the head of upgoing part
}
head = curr;
}
return head;
}
}
三部曲模版:
1.找终止条件。 什么情况下递归终止?没得交换的时候,递归就终止了呗。因此当链表只剩一个节点或者没有节点的时候,自然递归就终止了。
2.找返回值。 我们希望向上一级递归返回什么信息?由于我们的目的是两两交换链表中相邻的节点,因此自然希望交换给上一级递归的是已经完成交换处理,即已经处理好的链表。
3.本级递归应该做什么。 由于只考虑本级递归,所以这个链表在我们眼里其实也就三个节点:head、head.next、已处理完的链表部分。而本级递归的任务也就是交换这3个节点中的前两个节点,就很easy了。
单链表反转:
//like 1->2->3->4
//思路:把当前链表的head得下一个节点next插入到dummy的下一个节点中
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0); // create a new dummy head node
dummy.next = head;
while(head != null && head.next !=null ){
ListNode next = head.next; //head's next node
head.next = next.next; //make head 1 point to 3
next.next = dummy.next; //make 2 point to 1
dummy.next = next; //make dummy point to 2
}
return dummy.next;
}
}
单链表两两反转:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
while(head != null && head.next !=null ){
ListNode next = head.next;
head.next = next.next;
next.next = head;
pre.next = next;
pre = head;
head = head.next;
}
return dummy.next;
}
}
Reference: 单链表反转总结