LeetCode 25 Reverse Nodes in k-Group (C++, Python)

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

Solution C++


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
 * 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 (k < 2) return head;
        ListNode dummyNode(-1);
        dummyNode.next = head;
        head = &dummyNode;
        ListNode* p = head;
        while (1) {
            ListNode* q = p;
            for (int i = 0; i < k; ++i) {
                q = q->next;
                if (q == NULL) return head->next;
            }
            ListNode* nextp = p->next;
            while (p->next != q) {
                ListNode* d = p->next;
                p->next = p->next->next;
                d->next = q->next;
                q->next = d;
            }
            p = nextp;
        }
        return head->next;
    }
};

Solution Python


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @param {ListNode} head
    # @param {integer} k
    # @return {ListNode}
    def reverseKGroup(self, head, k):
        if k < 2: return head
        dummy = ListNode(0)
        dummy.next = head
        head = dummy
        p = head
        while True:
            q = p
            for i in range(k):
                q = q.next
                if q == None: return head.next
            nextp = p.next
            while p.next != q:
                d = p.next
                p.next = p.next.next
                d.next = q.next
                q.next = d
            p = nextp
        return head.next
        

Popular posts from this blog

How Django Works (4) URL Resolution

Python Class Method and Class Only Method

How Django works (3): Testing Server and Static Files Serving