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

LeetCode -- Reverse Nodes in K-Group

时间:2015-09-12 14:45:02      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

Question:

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

 

Analysis:

这是Swap Nodes的升级版本,将链表中的节点分为K组,每组中的节点顺序倒置,但组之间的顺序不变,如果剩余节点个数不足k个,则不颠倒。

思路是:首先生成一个头结点,防止找不到颠倒后的链首。然后设置三个节点,一个start,指向下一段链表的链首;一个p,指向本组链表的链首;一个q,寻找本组链表的结尾;一个val,指示目前本组已经遍历过几个节点。同时在整个程序中需要一个全局指针,便于寻找最终返回链表的链尾。这样,p指向的本组链表只需调用函数就地颠倒即可,然后加入返回链的链尾。

 

Answer:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    private ListNode tail;
    
    public ListNode reverseKGroup(ListNode head, int k) {
        if(head == null || head.next == null) 
            return head;
        if(k <= 1)
            return head;
        
        //创建一个首节点
        ListNode h = new ListNode(-1);
        tail = h;
        ListNode start = head, p = head, q = head; //start指向目前要颠倒结点的链首,q遍历结点找到k个结点
        while(q != null || q.next !=  null) {
            int val = 1;
            while(val < k && q.next != null) {
                q = q.next;
                val ++;
            }
            if(val < k && q.next == null) {
                tail = getTail();
                tail.next = start;
                return h.next;
            }
            start = q.next;
            q.next = null;
            ListNode jion = reverseList(p);
            tail = getTail();
            tail.next = jion;
            if(start == null) {
                return h.next;
            }
            p = start;
            q = start;
            
        }
        
        return h.next;
        
    }
    
    
        public ListNode getTail() {
            while(tail.next != null)
                tail = tail.next;
            return tail;
        }


        public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null)
            return head;
        ListNode h = head;
        while(head.next != null) {
            ListNode p = head.next;
            head.next = p.next;
            p.next = h;
            h = p;
        }
        return h;
    }
}

You are here! 
Your runtime beats 98.99% of java submissions.

(哈哈,感觉链表题目差不多OK了,可以不用看别人的思路,最终runtime也会大于98%以上,好有成就感~但是树,图等其他数据结构的还很差,要多练练!)

LeetCode -- Reverse Nodes in K-Group

标签:

原文地址:http://www.cnblogs.com/little-YTMM/p/4802876.html

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