zoukankan      html  css  js  c++  java
  • 蜗牛慢慢爬 LeetCode 25. Reverse Nodes in k-Group [Difficulty: Hard]

    题目

    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

    翻译

    相比 swap in pairs,这道题是每满 k 个进行一次倒转,如果最终不满 k 个则不进行倒转

    Hints

    Related Topics: Linked List

    solution
    可以利用递归,递归函数传入 head 和 k,和 swap in pairs 一样,只是先对 k 个进行判断,看是否到达链表的最后,如果是最后 k-1 个(或者少于k-1),则不进行倒转,返回 head;然后对由 head 开始的 k 个 Node 组成的小链表进行倒转就好了,倒转可以参考 看图理解单链表的反转 只不过 head.next 不指向 null,而是指向递归的 reverseKGroup(end,k) (end 是 head 之后的第 k+1 个)

    如果不利用递归其实也是一样的,只不过把递归的过程用 while 循环写出来,每到可以整除 k 的时候进行一次倒转

    代码

    Java

    //without recursion
    class Solution {
        public ListNode reverseKGroup(ListNode head, int k) {
             ListNode begin;
            if (head==null || head.next ==null || k==1)
            	return head;
            ListNode dummyhead = new ListNode(-1);
            dummyhead.next = head;
            begin = dummyhead;
            int i=0;
            while (head != null){
            	i++;
            	if (i%k == 0){
            		begin = reverse(begin, head.next);
            		head = begin.next;
            	} else {
            		head = head.next;
            	}
        }
        return dummyhead.next;
        }
        public ListNode reverse(ListNode begin, ListNode end){
        	ListNode curr = begin.next;
        	ListNode next, first;
        	ListNode prev = begin;
        	first = curr;
        	while (curr!=end){
        		next = curr.next;
        		curr.next = prev;
        		prev = curr;
        		curr = next;
        	}
        	begin.next = prev;
        	first.next = curr;
        	return first;
        }
    }
    
    //solution in discuss
    class Solution {
        public ListNode reverseKGroup(ListNode head, int k) {
            ListNode curr = head;
            int count = 0;
            while (curr != null && count != k) { // find the k+1 node
                curr = curr.next;
                count++;
            }
            if (count == k) { // if k+1 node is found
                curr = reverseKGroup(curr, k); // reverse list with k+1 node as head
                // head - head-pointer to direct part, 
                // curr - head-pointer to reversed part;
                while (count-- > 0) { // reverse current k-group: 
                    ListNode tmp = head.next; // tmp - next head in direct part
                    head.next = curr; // preappending "direct" head to the reversed list 
                    curr = head; // move head of reversed part to a new node
                    head = tmp; // move "direct" head to the next node in direct part
                }
                head = curr;
            }
            return head;
        }
    }
    
    

    Python

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def reverseKGroup(self, head, k):
            """
            :type head: ListNode
            :type k: int
            :rtype: ListNode
            """
            tmp = head
            if k<=1:
                return head
            for i in range(k):
                if tmp!=None:
                    tmp = tmp.next
                else:
                    return head
            p = head
            q = head.next
            r = None
            head.next = self.reverseKGroup(tmp,k)
            while q!=tmp:
                r = q.next
                q.next = p
                p = q
                q = r
            head = p
            return head
    
  • 相关阅读:
    一道网易面试题
    OC的引用计数
    ReplayKit2 采集音视频回调格式分析
    《剑指offer3- 从末尾到头打印链表》
    《剑指offer
    《剑指offer
    ReplayKit2:声音回调时间戳问题
    UILable在Autolayout模式下面自动调节字体大小
    建表手写语句
    oracle创建主键序列和在ibatis中应用
  • 原文地址:https://www.cnblogs.com/cookielbsc/p/7641186.html
Copyright © 2011-2022 走看看