25Reverse Nodes in k-Group

来源:互联网 发布:嵌入式好还是java好 编辑:程序博客网 时间:2024/05/21 15:59

题目链接:https://leetcode.com/problems/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->5For k = 2, you should return: 2->1->4->3->5For k = 3, you should return: 3->2->1->4->5

解题思路:
题目的意思是,将给定链表每 k 个元素划为一组,对每一组链表实现逆转,如果最后一组个数小于 k ,则保持其本来顺序不对其进行逆转。
采用的思路比较简单。将每一组(一组有 k 个结点元素)需要逆转的链表放到一个专门逆转链表的函数中进行逆转,将逆转后的链表挂接在新链表的尾部。当然啦,在逆转一个链表(一组 k 个结点的元素)之前,需要记录该链表后面(即,下一组)链表的第一个结点。
当 k 为 1 时,其实就是链表本身。直接返回链表可节约很多时间。

/** * 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) {        if(head == null || head.next == null || k == 1)            return head;        ListNode res = new ListNode(0);        ListNode p = res;        while(head != null) {            ListNode l = head;            ListNode r = head;            int j = 1;            while(r.next != null && j < k) {                r = r.next;                j ++;            }            head = r.next;            if(j == k) {                p.next = reverseSub(l, k);                p = l;            } else {                p.next = l;            }        }        return res.next;    }    public ListNode reverseSub(ListNode head, int k) {        ListNode res = new ListNode(0);        while(k -- != 0) {            ListNode p = head;            head = head.next;            p.next = res.next;            res.next = p;        }        return res.next;    }}
81 / 81 test cases passed.Status: AcceptedRuntime: 332 ms
0 0