Leetcode: Reverse Nodes in k-Group
2014-02-04 22:47
429 查看
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list:
For k = 2, you should return:
For k = 3, you should return:
/**
* 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 *tmp = NULL, *last = NULL, *prev = NULL;
ListNode *cur = head;
ListNode *dummy = new ListNode(-1);
head = dummy;
while (cur != NULL) {
last = cur;
int count = 0;
while (count < k - 1 && cur != NULL) {
cur = cur->next;
++count;
}
if (cur == NULL) {
head->next = last;
break;
}
++count;
cur = last;
while (count-- > 0 && cur != NULL) {
tmp = cur->next;
cur->next = prev;
prev = cur;
cur = tmp;
}
head->next = prev;
head = last;
prev = NULL;
}
head = dummy->next;
delete dummy;
return head;
}
};
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For 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
比较简单,写了半个多小时,在面试中是不可接受的。应该把reverse单独抽出来做一个函数,这样可以简化逻辑,加快切题速度。
/**
* 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 *tmp = NULL, *last = NULL, *prev = NULL;
ListNode *cur = head;
ListNode *dummy = new ListNode(-1);
head = dummy;
while (cur != NULL) {
last = cur;
int count = 0;
while (count < k - 1 && cur != NULL) {
cur = cur->next;
++count;
}
if (cur == NULL) {
head->next = last;
break;
}
++count;
cur = last;
while (count-- > 0 && cur != NULL) {
tmp = cur->next;
cur->next = prev;
prev = cur;
cur = tmp;
}
head->next = prev;
head = last;
prev = NULL;
}
head = dummy->next;
delete dummy;
return head;
}
};
相关文章推荐
- Palindrome Number
- Max Points on a Line
- Evaluate Reverse Polish Notation
- Sort List
- Insertion Sort List
- LRU Cache
- Binary Tree Postorder Traversal
- Binary Tree Preorder Traversal
- Reorder List
- Linked List Cycle
- Linked List Cycle II
- Word Break
- Word Break II
- Copy List with Random Pointer
- Single Number
- Single Number II
- Candy
- Gas Station
- Clone Graph
- Palindrome Partitioning