reverse-nodes-in-k-group 1.0.0
Reverse Nodes in k-Group
Loading...
Searching...
No Matches
Solution Class Reference

Public Member Functions

ListNodereverseKGroup (ListNode *head, int k)
 

Detailed Description

Definition at line 17 of file main.cpp.

Member Function Documentation

◆ reverseKGroup()

ListNode * Solution::reverseKGroup ( ListNode head,
int  k 
)
inline

Definition at line 20 of file main.cpp.

21 {
22 if (!head || k == 1) return head;
23
24 // new list to reconstruct the reversed k-groups
25 list<ListNode*> new_list;
26
27 // k-sized stack for reversing groups
28 stack<ListNode*> s;
29
30 ListNode* ptr = head;
31 bool stop = false;
32 while (1)
33 {
34 // skipping k times to establish if full k-sized group is present
35 ListNode* fast = ptr;
36 for (int i = 0; i < k; ++i)
37 {
38 if (fast == nullptr)
39 {
40 stop = true;
41 break;
42 }
43 fast = fast->next;
44 }
45 if (stop)
46 break;
47
48 // pushing k-sized group to stack
49 for (int i = 0; i < k; ++i)
50 {
51 s.push(ptr);
52 ptr = ptr->next;
53 }
54
55 // emptying stack into new list
56 while (!s.empty())
57 {
58 new_list.push_back(s.top());
59 s.pop();
60 }
61 }
62
63 // append the rest normally
64 while (ptr != nullptr)
65 {
66 new_list.push_back(ptr);
67 ptr = ptr->next;
68 }
69
70 // reconstruct the list from head
71 head = new_list.front();
72 new_list.pop_front();
73 ptr = head;
74 for (ListNode* node: new_list)
75 {
76 ptr->next = node;
77 ptr = ptr->next;
78 }
79 ptr->next = nullptr;
80 return head;
81 }
Definition for singly-linked list.
Definition main.cpp:9
ListNode * next
Definition main.cpp:11

References ListNode::next.

Referenced by main().


The documentation for this class was generated from the following file: