LeetCode 25. Reverse Nodes in k-Group

来源:互联网 发布:淘宝达人申请直播入口 编辑:程序博客网 时间:2024/05/29 11:59

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

k is a positive integer and is less than or equal to the length of the linked 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

Subscribe to see which companies asked this question.

对一个链表,每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) {        if(head==null||k==1){            return head;        }        int len = 0;        ListNode p = head;        while(p!=null){            len++;            p = p.next;        }        int time = len/k;        ListNode q = head;        ListNode beg = head;        ListNode tem = null;        ListNode ans = new ListNode(0);        p = ans;        for(int i=0;i<len;i++){            if(time>0){            if((i+1)%k==0){                tem = q.next;                q.next = null;                p.next = reserve(beg);                time--;                while(p.next!=null){                    p = p.next;                }                beg = tem;                q = tem;            }            else{                q = q.next;            }            }            else{                p.next = q;            }        }        return ans.next;    }    public ListNode reserve(ListNode head){        ListNode p = head;        ListNode pre = null;        ListNode tem = p;        while(p!=null){            tem = p.next;            p.next = pre;            pre = p;            p = tem;        }        return pre;    }}


0 0