題目描述
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
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
Note:
Only constant extra memory is allowed.
You may not alter the values in the list's nodes, only nodes itself may be changed.
代碼
別人家的代碼永遠都這麼優雅。
/**
* 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 (head == NULL || k == 1) return head;
ListNode* t = head;
for (int i=0; i<k-1; ++i) {
t = t->next;
if (t == NULL) return head;
}
ListNode* nxt = t->next;
t->next = NULL;
t = reverseKGroup(nxt, k);
ListNode* s = head;
while(s != NULL) {
nxt = s->next;
s->next = t;
t = s;
s = nxt;
}
return t;
}
};
自己寫的代碼卻又臭又長。也想用dfs再寫一版來着,寫完這個好累。
/**
* 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 (head == NULL || k == 1) return head;
ListNode* res = head;
ListNode* st = res;
ListNode* ed = st;
ListNode* preed = NULL;
int cnt = 1;
while(res != NULL) {
res = res->next;
cnt++;
if (cnt % k == 0 && res != NULL) {
ListNode* nxt = res->next;
vector<ListNode*> tmp = reverse(st, res);
st = tmp[0];
ed = tmp[1];
if (cnt == k) {
head = st;
}
ListNode* t = head;
if (preed == NULL) {
preed = ed;
}else {
preed->next = st;
preed = ed;
}
ed->next = nxt;
t = head;
st = nxt;
res = nxt;
cnt++;
}
}
return head;
}
vector<ListNode*> reverse(ListNode* st, ListNode* ed) {
ListNode* pre = st;
ListNode* cur = st->next;
ListNode* nxt = ed->next;
while(cur != NULL) {
ListNode* nxt = cur->next;
cur->next = pre;
if (cur == ed) break;
pre = cur;
cur = nxt;
}
st->next = nxt;
return {ed, st};
}
};