码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode】Reverse Nodes in k-Group 解题报告

时间:2014-12-17 18:37:28      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:链表   反转链表   reverse nodes in k-g   

【题目】

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

【解析】

题意:把原始链表k个k个的反转,如果最后剩余的不到k个结点,那么保持不变。

没什么特殊算法,我觉得重点在于怎么不用额外的空间反转k个结点,用三个指针 curtail, curhead, posthead,curtail 指向反转后的尾结点,curhead 指向反转后的头结点,posthead 是反转过程中 curhead 的后一个结点,用于辅助反转。这个方法可以对照题目 【LeetCode】Reverse Linked List II 解题报告 

/**
 * 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 < 2) return head;
        
        ListNode prehead = new ListNode(0);
        prehead.next = head;
        int cnt = 0;
        ListNode node = head;       //迭代结点
        ListNode lasttail = prehead;//上次k个结点反转后的尾结点
        ListNode curtail = head;    //这次要反转的k个结点的尾结点
        ListNode curhead = head;    //这次要反转的k个结点的头结点
        ListNode posthead = null;   //这次要反转的k个结点的头结点后面的一个结点
        while (node != null) {
            cnt++;
            node = node.next;
            
            //反转这k个结点
            if (cnt == k) {
                ListNode tmp = curtail.next;
                while (tmp != node) {
                    posthead = curhead;
                    curhead = tmp;
                    tmp = tmp.next;
                    curhead.next = posthead;
                }
                lasttail.next = curhead;//把这次反转的k个结点接到上次的k个结点后
                lasttail = curtail;
                curtail = node;
                curhead = node;
                cnt = 0;
            }
            
        }
        
        //如果后面还有少于k个的结点,直接把其接到之前的链表上
        lasttail.next = curhead;
        
        return prehead.next;
    }
}


相关题目: 【LeetCode】Reverse Linked List II 解题报告 

【LeetCode】Reverse Nodes in k-Group 解题报告

标签:链表   反转链表   reverse nodes in k-g   

原文地址:http://blog.csdn.net/ljiabin/article/details/41983351

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!