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

25. Reverse Nodes in k-Group

时间:2019-02-02 10:16:26      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:html   sub   positive   memory   mod   osi   int   rev   更新   

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.

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

Note:

  • Only constant extra memory is allowed.
  • You may not alter the values in the list‘s nodes, only nodes itself may be changed.

解题思路:https://leetcode.windliang.cc/leetCode-25-Reverse-Nodes-in-k-Group.html

public ListNode reverseKGroup(ListNode head, int k) {
    if (head == null)
        return null;
    ListNode sub_head = head;
    ListNode dummy = new ListNode(0);
    dummy.next = head;
    ListNode tail = dummy;
    ListNode toNull = head;
    while (sub_head != null) {
        int i = k;
        //找到子链表的尾部
        while (i - 1 > 0) {
            toNull = toNull.next;
            if (toNull == null) {
                return dummy.next;
            }
            i--;
        }
        ListNode temp = toNull.next;
        //将子链表断开
        toNull.next = null;
        ListNode new_sub_head = reverse(sub_head); 
        //将倒置后的链表接到 tail 后边
        tail.next = new_sub_head;
        //更新 tail 
        tail = sub_head; //sub_head 由于倒置其实是新链表的尾部
        sub_head = temp;
        toNull = sub_head;
        //将后边断开的链表接回来
        tail.next = sub_head;
    }
    return dummy.next;
}
public ListNode reverse(ListNode head) {
    ListNode current_head = null;
    while (head != null) {
        ListNode next = head.next;
        head.next = current_head;
        current_head = head;
        head = next;
    }
    return current_head;
}

很好很强大,我很饿

25. Reverse Nodes in k-Group

标签:html   sub   positive   memory   mod   osi   int   rev   更新   

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/10347469.html

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