leetcode: Reverse Nodes in k-Group

来源:互联网 发布:移动网络变成电信 编辑:程序博客网 时间:2024/06/05 15:13

题目要求我们把链表中每k个节点购车的链反转一下。   思路很简单,链表扫描计数,每k个再扫描一遍反转,时间消耗O(n);空间消耗也是单位级别。    这里需要注意的是k链表还在原链表中,反转链表时要记录一些节点信息以确保反转后的k链表之间连接正确(k链表起始节点,k链表前一节点,k链表后一节点),细节要考虑清楚


/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode reverseKGroup(ListNode head, int k) {        if( head == null || k== 0 )        {            return head;        }        boolean first=true;        ListNode res = head;        ListNode st = head;        ListNode p = head;        ListNode stpre = null;        int count=0;        while( p != null )        {            count++;            if( count == k )            {                ListNode next = p.next;                ListNode tmp1=st;                ListNode tmp2=st.next;                for( int i=1;i<k;i++ )                {                    ListNode tmpNext = tmp2.next;                    tmp2.next = tmp1;                    tmp1 = tmp2;                    tmp2 = tmpNext;                }                if( first == true )                {                    res = tmp1;                    first = false;                }                if( stpre != null )                {                    stpre.next = tmp1;                }                stpre = st;                st.next = next;                st = next;                count=0;                p = next;            }            else            {                p = p.next;            }        }        return res;    }}


0 0