Reverse Nodes in k-Group
问题描述:
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
实现的过程用到了递归思想
下面贴上代码,代码里面有对应的注释
好了上代码
class ListNode{
int val;
ListNode next;
ListNode(int x){
val = x;
}
}
class Solution{
public ListNode reverseKGroup(ListNode head, int k){
ListNode currentListNode = head;
int cnt = 0;
//从开始数K个一组处理
while(currentListNode != null && cnt != k){
currentListNode = currentListNode.next;
cnt = cnt + 1;
}
//如果cnt = k 跳出while循环了, 那么就需要处理了
if(cnt == k){
//递归掉处理下面一个K个节点的组,我们的思想是处理之后那K个节点的顺序已经是符合题目要求的了,这时候用currentListNode继续指向调整过后的K各节点的头
//所以这里赋值左边的仍然是currentListNode
currentListNode = reverseKGroup(currentListNode, k);
//如果能执行完上面这一行代码,说明递归返回了
while(cnt > 0){
ListNode tmp = head.next;
head.next = currentListNode;
//将currentListNode 和 head 向前移动一个节点
currentListNode = head;
head = tmp;
cnt--;
}
//经过while的处理,这时候跳出while的时候 head已经移动出去当前K个点了,所以给予调整
head = currentListNode;
}
return head;
}
}
这个是上面的一个特例,所以对应的就有特殊的解法
就是直接交换两个节点。但还是用到了递归的思想
public class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null) return head;
ListNode temp = head.next;
head.next = swapPairs(temp.next);
temp.next = head;
return temp;
}
}
先断掉head.next, 在这之前先保存在temp里面,保存之后将后面的递归返回节点赋值给head.next
下来改变 head.next的next的值, 使他为head。这样子就交换了前两个点,同时和后面的也连接上了
最后返回新链的头结点。这里为temp