leetcode-25. Reverse Nodes in k-Group

来源:互联网 发布:ubuntu find file 编辑:程序博客网 时间:2024/05/20 17:58

leetcode-25. 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

之前有一道24. Swap Nodes in Pairs
思路基本上一样,只是泛化一下:
首先,链表的题加哑节点基本上是通行的方法了
其次,判断一下是否有足够的节点来进行翻转,如果有则进行k个节点的翻转,如果没有则直接返回。
最后,翻转的时候和两节点的类似,需要建立k大小的数组来储存哑节点之后的k个需要翻转的节点,翻转之后移动哑节点到最后的一个翻转完成的节点的位置,然后迭代。

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode reverseKGroup(ListNode head, int k) {        ListNode d = new ListNode(0);        ListNode ret = d;        d.next = head;        helper(d,k);        return ret.next;    }    private ListNode helper(ListNode d, int k){        if(k<=1) return d;        int t = k;        ListNode p = d;        while(p.next!=null){            p = p.next;            if(--t==0) break;        }        if(t==0){            ListNode[] list = new ListNode[k];            ListNode tmp = d;            for(int i = 0 ; i < k ; i++){                tmp = tmp.next;                list[i] = tmp;            }            tmp = d;            tmp.next = list[k-1];            list[0].next = list[k-1].next;            for(int i = 1 ; i < k ; i++){                list[i].next = list[i-1];            }            tmp = list[0];            helper(tmp,k);        }        return d;    }}
0 0
原创粉丝点击