[leetcode]Reverse Nodes in k-Group 反转以k个节点为一组的链表

来源:互联网 发布:淘宝衣服拍摄 编辑:程序博客网 时间:2024/04/29 12:09

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

这个题其实挺简单,思路是:

既然K=2 就是2个一组反转,反转后的点又指向了之后的节点,那么我们就知道了:

(1)首先得把链表的长度求出来 要是K=链表长度(len),那就是整个链表圈反转,要是小于,那我们只反转k个节点。

(2)反转了K个,那len-k个怎么办,我们可以想到用递归来求解,把剩下的节点扔到递归里,让它们自己算

那么递归的base case我们肯定要让head不为空,并且长度大于K,否则就返回null

每次都算长度太坑爹,肯定是一开始算好,把len当参数,给子问题。那么我们就可以再写一个带len(链表长度)的函数

(3)递归的细节

   那我们最后返回的头应该是什么,肯定是第一次以K为单位反转的头,例如k=2 1->2->3->4->5,那么返回2->1->.. 

    那么反转节点的末尾就是:子问题,长度为3的链表,依次类推

最后只剩下5一个点,传进函数后根据base case直接返回这个点就行

public class Solution {    public ListNode reverseKGroup(ListNode head, int k) {               return reverseK(head, k, getLength(head));            }        public ListNode reverseK(ListNode head, int k, int len){        if(k==1 || k>len || head==null) return head;        int i=2;        ListNode next=head.next;        ListNode pre=head;        head.next=null;        ListNode dummy=head;        while(i<=k){            head=next;             next=next.next;            head.next=pre;            pre=head;            head=next;            i++;        }        dummy.next=reverseK(head, k, len-k);        return pre;            }        public int getLength(ListNode head){        int len=0;        while(head!=null){            len++;            head=head.next;        }        return len;    }}


0 0
原创粉丝点击