Skip to content

Commit f273425

Browse files
Add files via upload
1 parent 171e6ff commit f273425

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
// 其实并不难,就是比较麻烦,如果非要说技巧,应该是单链表翻转的时候如何把头结点的next指针置空
2+
// Runtime: 16 ms, faster than 96.91% of C++ online submissions for Reverse Nodes in k-Group.
3+
// Memory Usage: 9.9 MB, less than 35.48% of C++ online submissions for Reverse Nodes in k-Group.
4+
5+
/**
6+
* Definition for singly-linked list.
7+
* struct ListNode {
8+
* int val;
9+
* ListNode *next;
10+
* ListNode(int x) : val(x), next(NULL) {}
11+
* };
12+
*/
13+
14+
class Solution
15+
{
16+
public:
17+
ListNode* reverseKGroup(ListNode* head, int k)
18+
{
19+
// 首先统计一下链表的长度
20+
int length = 0;
21+
ListNode* temp = head;
22+
while (temp)
23+
{
24+
++length;
25+
temp = temp->next;
26+
}
27+
28+
// 边界条件处理
29+
if (head == nullptr || k <= 0 || k > length) return head;
30+
31+
ListNode dummyHead(666);
32+
ListNode* preHead = &dummyHead;
33+
34+
int numOfLeft = length;
35+
ListNode *preNode = nullptr, *curNode = head, *nextNode = nullptr;
36+
37+
while (numOfLeft)
38+
{
39+
if (numOfLeft < k) break;
40+
41+
ListNode *curHead = curNode, *curTail = nullptr;
42+
43+
for (int i = 0; i < k; ++i)
44+
{
45+
nextNode = curNode->next;
46+
curNode->next = preNode;
47+
48+
preNode = curNode;
49+
curNode = nextNode;
50+
51+
--numOfLeft;
52+
}
53+
54+
curTail = preNode;
55+
56+
preHead->next = curTail;
57+
curHead->next = curNode;
58+
59+
preHead = curHead;
60+
}
61+
62+
return dummyHead.next;
63+
}
64+
};

0 commit comments

Comments
 (0)