现在的位置: 首页 > 综合 > 正文

LeetCode OJ –问题与解答 Reverse Nodes in k-Group

2014年04月05日 ⁄ 综合 ⁄ 共 1340字 ⁄ 字号 评论关闭

题目


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 ,逆这部分链表一次。


思路


1 一开始没理解题目意思,以为是只有把前半部分k给逆转就行了。结果wrong了,不过好在,前面的转换思路对我后面解题也是有帮助的。

2 关键点有两个:

a 什么时候逆转?

b 怎么处理逆转的细节?

3 关于什么时候逆转,很简单,有个计数器,每次碰到对k取余为0的时候,就可以把前半部分逆转了。

4 处理逆转的细节:

a 一般这类问题,需要4个关键点,外面的起始点,里面的起始点,里面的终点,外面的终点(或者说外面下个起始点)。

b  一般选取参数,都靠近之前的选取比较好,因为有next嘛,后面的可以增加变量来存储。所以这里参数用(外面的起始点,里面的终点)

c  在处理内部逆转之前,之后,把几个接头给处理好。

d 处理内部逆转的时候,有固定的方法,我的固定方法已经写过几遍,基本不会变了。


代码


public class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if(k<=1||head==null){
            return head;
        }
        ListNode dummy = new ListNode(Integer.MIN_VALUE);
        dummy.next=head;
        ListNode pre = dummy;
        ListNode cur = head;
        for(int i=1;cur!=null;i++){
            if(i%k==0){
                pre = reverse(pre,cur);
                cur = pre.next;
            }
            else{
                cur=cur.next;
            }
        }
        return dummy.next;
        
    }
   // outpre inpre inend  outbound 分别代表4个关键点
    public ListNode reverse(ListNode outpre ,ListNode inend){
        ListNode inpre = outpre.next;
        ListNode cur = inpre.next;
        ListNode outbound = inend.next;
       ListNode repre = inpre;
        outpre.next=inend;
        while(cur!=outbound){
            ListNode temp = cur.next;
            cur.next=inpre;
            inpre=cur;
            cur= temp ;
        }
        repre.next=outbound;
        return repre;
    }
}

抱歉!评论已关闭.