【Leetcode】25.Reverse Nodes in k-Group

Question:

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

Tips:

给定一个链表,每k个结点进行一次翻转,最后若剩余不足k个结点,不进行操作,直接接在后面。

思路:

举例说1->2->3->4->5->6;  k=4;

设置一个int型变量count,一个指针指向头结点。每走过一个结点count++。当count%k!=0 指针继续后移,如果count%k==0 则从头结点开始,到head.next结束,传入reverse函数,进行翻转。注意插入的部分链表,第一个跟最后一个不进行翻转,传入只是为了将翻转的链表连接起来。

进行第一次reverse 传入的链表是(-1->1->2->3->4->5).返回(-1->4->3->2->1->5)

代码:

public ListNode reverseKGroup(ListNode head, int k) {
        if(head==null ||head.next==null ||k==1) return head;
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode begin = dummy;
        int count=0;
        while (head != null) {
            count++;
            if(count%k==0){
                //头结点+需要反转的一整组结点+下一组的第一个结点,全部传入reverse
                begin=reverse(begin,head.next);
                head=begin.next;
            }else{
                head=head.next;
            }
        }
        return dummy.next;
    }

    public ListNode reverse(ListNode begin, ListNode end) {
        ListNode pre=begin;
        ListNode cur=begin.next;
        //first记录该组第一个结点,反转后为最后一个结点。
        ListNode first=cur;
        while(cur!=end){
            ListNode next=cur.next;
            cur.next=pre;
            pre=cur;
            cur=next;
        }
        //pre为该组翻转后得第一个结点,之后还需要将pre接在begin之后。
        begin.next=pre;
        //cur为下一组的结点,需要将其接在该组翻转后最后一个结点之后。
        first.next=cur;
        return first;
    }
posted @ 2018-03-05 11:32  于淼  阅读(100)  评论(0编辑  收藏  举报