zoukankan      html  css  js  c++  java
  • [Linked List]Reverse Nodes in k-Group

    Total Accepted: 48614 Total Submissions: 185356 Difficulty: 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

     
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* reverseList(ListNode* head)
        {
            ListNode* newHead=NULL,*p=head,*next=NULL;
            while(p){
                next    = p->next;
                p->next = newHead;
                newHead = p;
                p       = next;
            }
            return newHead;
        }
        ListNode* reverseKGroup(ListNode* head, int k) {
            if(k<=1){
                return head;
            }
            ListNode *pre=NULL,*next=NULL;
            ListNode *cur=head;
            ListNode *reverseHead = NULL;
            int cnt = 0;
            while(cur){
                if(cnt==0){
                    reverseHead = cur;
                }
                next = cur->next;
                ++cnt;
                if(cnt==k){
                    cur->next=NULL;
                    ListNode *newHead = reverseList(reverseHead);
                    pre ? pre->next = newHead : head=newHead;
                    reverseHead->next = next;
                    pre = reverseHead;
                    cur = next;
                    cnt = 0;
                }else{
                    cur = cur->next;
                }
            }
            return head;
        }
    };
  • 相关阅读:
    字符序列(characts)
    装载问题(load)
    哈密顿路
    犯罪团伙
    回溯算法
    维修机器人
    旅行计划
    皇后游戏
    运输
    亲身实测可用的java实现wordxlsxpdf文件下载功能
  • 原文地址:https://www.cnblogs.com/zengzy/p/5041371.html
Copyright © 2011-2022 走看看