1. 程式人生 > >#Leetcode# 25. Reverse Nodes in k-Group

#Leetcode# 25. Reverse Nodes in k-Group

rem linked ans brush it is style ref ron !=

https://leetcode.com/problems/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.

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.

代碼:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        if(!head) return NULL;
        int cnt = 0;
        ListNode *cur = new ListNode(-1);
        ListNode *dummy = cur;
        vector<int> a, b;
        ListNode *pre = head;
        while(pre) {
            a.push_back(pre -> val);
            pre = pre -> next;
        }
        cnt = a.size();
        if(k > cnt) return head;
        //k %= cnt;
        if(!k) return reverseList(head);
        int rec = cnt / k;
        for(int i = 0; i < rec * k; i += k) {
            for(int j = i + k - 1; j >= i; j --) {
                b.push_back(a[j]);
            }
        }
        if(rec * k != cnt)
            for(int i = rec * k; i < cnt; i ++)
                b.push_back(a[i]);
        for(int i = 0; i < b.size(); i ++) {
            ListNode *t = new ListNode(b[i]);
            t -> next = NULL;
            dummy -> next = t;
            dummy = dummy -> next;
        }
        return cur -> next;
    }
    ListNode* reverseList(ListNode* head) {
        ListNode *revhead = NULL;
        ListNode *pnode = head;
        ListNode *pre = NULL;
        
        while(pnode) {
            if(!pnode -> next)
                revhead = pnode;
            
            ListNode *nxt = pnode -> next;
            pnode -> next = pre;
            pre = pnode;
            pnode = nxt;
        }
        return revhead;
    }
};

  就是很簡單的每 k 個反轉一下 但是和之前做過的類似題目不一樣的是 k 就是 k 不要 k%= cnt 會 WA 太久不寫鏈表寫的有點吃力啊 嗚嗚嗚

#Leetcode# 25. Reverse Nodes in k-Group