Skip to content

Commit 5ed6304

Browse files
authored
Create 2074.Reverse-Nodes-in-Even-Length-Groups.cpp
1 parent 8588253 commit 5ed6304

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode() : val(0), next(nullptr) {}
7+
* ListNode(int x) : val(x), next(nullptr) {}
8+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9+
* };
10+
*/
11+
class Solution {
12+
public:
13+
ListNode* reverseEvenLengthGroups(ListNode* head)
14+
{
15+
vector<ListNode*>heads;
16+
vector<int>lens;
17+
18+
ListNode* h = head;
19+
int len = 1;
20+
21+
while (1)
22+
{
23+
heads.push_back(h);
24+
int count = 1;
25+
for (int i=0; i<len-1; i++)
26+
{
27+
if (h->next == NULL) break;
28+
h = h->next;
29+
count++;
30+
}
31+
lens.push_back(count);
32+
33+
if (h->next==NULL) break;
34+
ListNode* nxt = h->next;
35+
h->next = NULL;
36+
h = nxt;
37+
len++;
38+
}
39+
40+
for (int i=0; i<heads.size(); i++)
41+
{
42+
if (lens[i]%2==0)
43+
heads[i] = reverseLinkedList(heads[i]);
44+
}
45+
46+
47+
for (int i=0; i<heads.size()-1; i++)
48+
{
49+
ListNode* p = heads[i];
50+
while (p->next!=NULL)
51+
p = p->next;
52+
p->next = heads[i+1];
53+
}
54+
55+
return heads[0];
56+
}
57+
58+
ListNode* reverseLinkedList(ListNode* head)
59+
{
60+
ListNode* h = head;
61+
ListNode* last = NULL;
62+
while (h!=NULL)
63+
{
64+
ListNode* nxt = h->next;
65+
h->next = last;
66+
last = h;
67+
h = nxt;
68+
}
69+
return last;
70+
}
71+
};

0 commit comments

Comments
 (0)