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;
        }
    };
  • 相关阅读:
    Acdream 1174 Sum 暴力
    Acdream 1114 Number theory 莫比乌斯反演
    Acdream 1007 快速幂,模乘法
    UVa 10023
    UVa 11027
    UVa 11029
    UVa 10820
    UVa 10791
    UVa 11121
    UVa 106
  • 原文地址:https://www.cnblogs.com/zengzy/p/5041371.html
Copyright © 2011-2022 走看看