【leetcode】Reverse Nodes in k-Group (hard)☆

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

思路:

我的想法是把每一组的翻转单独列出来,每次翻转时都顺次翻转跟着的元素,如果遇到数目不够的再把后面的翻转回去。

代码略长...

//start time = 10:36
//end time = 13:27
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <stack>
using namespace std;

 struct ListNode {
      int val;
      ListNode *next;
      ListNode(int x) : val(x), next(NULL) {}
  };

class Solution {
public:
    ListNode *reverseKGroup(ListNode *head, int k) {
        ListNode * anshead = NULL; //答案头结点
        ListNode * anstail = NULL; //已经翻转过的链表的尾结点
        ListNode * parthead = NULL; //当前组翻转后的头结点
        ListNode * parttail = NULL; //当前组翻转后的尾结点
        ListNode * nxthead = NULL; //下一次翻转时的头结点

        int num = reverse(head, k, nxthead, parthead, parttail);
        //链表总长度不足k 把部分翻转的再还原回去
        if(num != 0)
        {
            head = parthead;
            reverse(head, num, nxthead, parthead, parttail);
            return parthead;
        }
        anshead = parthead; //确定答案头结点是第一次翻转后的头结点
        //只要后面还有非空指针 就接着翻转下一组k个元素
        while(nxthead != NULL)
        {
            anstail = parttail;
            head = nxthead;
            num = reverse(head, k, nxthead, parthead, parttail);
            if(num != 0) //该组不足k个元素 恢复后面的元素
            {
                head = parthead;
                reverse(head, num, nxthead, parthead, parttail);
                anstail->next = parthead;
                return anshead;
            }

            anstail->next = parthead; //把新翻转后的组加在答案的末尾
        }

        return anshead;
    }

    //翻转一组k个元素
    //输入: head 当前需要翻转链表的头结点   k 需要翻转的个数
    //输出: nxthead 下一次翻转时的头结点  parthead 当前组翻转后的头结点 parttail 当前组翻转后的尾结点    //返回 0表示完成翻转 返回非0表示不足k个
    int reverse(ListNode *head, int k, ListNode * &nxthead, ListNode * &parthead, ListNode *&parttail)
    {
        //头为空 直接返回
        if(head == NULL)
        {
            parthead = head;
            return 0;
        }

        parttail = head; //当前k个元素组的链尾
        parthead = head; //当前组的链头
        ListNode * cur = head->next; //当前待翻转的元素
        parttail->next = NULL;

        int n = k - 1;
        while(n--)
        {
            //不够k个 把已经翻转过的转回来
            if(cur == NULL)
            {
                return k - n + 1; //返回需要在尾部翻转回的链表长度
            }

            ListNode * nxt = cur->next;
            cur->next = parthead;
            parthead = cur;
            cur = nxt;
        }

        nxthead = cur;

        return 0;
    }
};

看了别人精简的代码,每次先循环判断当前组是否够k个元素,省去了判断是否需要重新翻转的麻烦

O(n) and O(1) of course it is.

Each time when starting, find the future new head (nh) and save the old head of the next to-be-reversed list. If existed, nh is k step far from oh. Then reverse the list from oh to nh and save its tail for combination.

Example:

1-2-3-4-5

iter1: oh = 1, nh = 2 2-1-3-4-5

iter2: oh = 3, nh = 4 2-1-4-3-5

iter3: oh = 5, nh = 0 2-1-4-3-5

 ListNode *reverseKGroup(ListNode *head, int k) {
    if(!head || !head->next || k==1) return head;
    int i=k;
    ListNode * p0 = head, * p1 = head->next, * p2 = 0, * t = 0, * ret = head, *oh, * nh;
    while(p1)
    {
        oh = nh = p0;
        i = k;
        while(--i && nh)
            nh = nh->next; //判断后面是否够k个元素
        if(!nh) break; //不够直接跳出
        i = k;
        while(--i) //翻转后面的k个元素
        {
            p2 = p1->next;
            p1->next = p0;
            p0 = p1;  //p0是一组的头结点
            p1 = p2;
        }
        if(t) //已经翻转后的尾部加上新的元素
            t->next = p0;
        else
            ret = p0; //确定头结点
        p0 = oh;
        t = p0; //最初当前组的头结点oh 是现在的尾部

        p0 = p0->next = p1; //新的待判断的头结点
        if(p1)
            p1 = p1->next; //新的头结点的下一个结点
    }
    return ret;
}
时间: 2024-11-10 14:19:47

【leetcode】Reverse Nodes in k-Group (hard)☆的相关文章

【leetcode】Reverse Words in a String (python)

陆陆续续几个月下来,终于把题刷完了,过程中遇到的python的题解很少,这里重新用python实现下,所以题解可能都是总结性的,或者是新的心得,不会仅针对题目本身说的太详细. def reverseWords(self, s): s = ' '.join(s.split()[::-1]) return s [ : :  -1 ] 是将元素进行翻转 [leetcode]Reverse Words in a String (python),布布扣,bubuko.com

【leetcode】reverse Nodes in k-groups

问题: 给定一个链表的头指针,以及一个整数k,要求将链表按每k个为一组,组内进行链表逆置.少于k个的部分不做处理. 分析: 个人觉得问题的重点是熟悉链表的就地逆置操作,就是头插法.其他的考察点如果还有的话,就的细心程度. 实现: void reverseList(ListNode *&pre, ListNode *head) { ListNode *tail = NULL; while (head) { ListNode* next = head->next; head->next =

【leetcode】Pascal&#39;s Triangle I &amp; II (middle)

Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5,Return [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] 思路:杨辉三角,直接按规律生成即可 vector<vector<int> > generate(int numRows) { vector<vector<int>>

【leetcode】Reverse Nodes in k-Group

Reverse Nodes in k-Group 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 valu

【leetcode】Binary Tree Right Side View(middle)

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. For example:Given the following binary tree, 1 <--- / 2 3 <--- \ 5 4 <--- You should return [1, 3, 4].

【leetcode】Median of Two Sorted Arrays(hard)★!!

There are two sorted arrays A and B of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). 思路: 难,知道用分治算法,却不知道怎么用.只好看答案. 基本的思路是如果中位数是第K个数,A[i]如果是中位数,那么A[i]已经大于了i个数,还应大于K - i - 1个

【leetcode】Bitwise AND of Numbers Range(middle)

Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive. For example, given the range [5, 7], you should return 4. 思路: 先找前面二进制相同的位,后面不相同的位相与一定为0. 比如: 1111001 1110011 从0011 - 1001 中间一定会经

【leetcode】Remove Duplicates from Sorted List (easy)

Given a sorted linked list, delete all duplicates such that each element appear only once. For example,Given 1->1->2, return 1->2.Given 1->1->2->3->3, return 1->2->3. 思路: 简单题,没什么好说的. class Solution { public: ListNode *deleteDupl

【leetcode】Sum Root to Leaf Numbers(hard)

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. An example is the root-to-leaf path 1->2->3 which represents the number 123. Find the total sum of all root-to-leaf numbers. For example, 1 / 2 3 T