-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0025-Reverse-nodes-in-k-group.cs
More file actions
56 lines (46 loc) · 1.36 KB
/
0025-Reverse-nodes-in-k-group.cs
File metadata and controls
56 lines (46 loc) · 1.36 KB
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
using Common;
using System;
using System.Collections.Generic;
using System.Text;
namespace Solution._0025.Reverse_nodes_in_k_group
{
public class _0025_Reverse_nodes_in_k_group
{
public ListNode ReverseKGroup(ListNode head, int k)
{
if (head == null || k <= 1) return head;
Stack<int> stack = new Stack<int>();
ListNode curr = head;
ListNode node = new ListNode();
ListNode res = node;
while (curr != null)
{
stack.Push(curr.val);
if (stack.Count == k)
{
while (stack.Count > 0)
{
ListNode pop = new ListNode(stack.Pop());
node.next = pop;
node = node.next;
}
}
curr = curr.next;
}
if (stack.Count > 0)
{
Stack<int> s = new Stack<int>();
// reverse stack
while (stack.Count > 0)
s.Push(stack.Pop());
// add tail
while (s.Count > 0)
{
node.next = new ListNode(s.Pop());
node = node.next;
}
}
return res.next;
}
}
}