您的位置:首页 > Web前端 > Node.js

LeetCode OJ - Reverse Nodes in k-Group

2014-08-11 22:31 267 查看
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: 
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

分析:k步反转,不足k步不反转。思路比较简单,对于k个元素为一组,维护该组之前的一个指针pre_left。遍历k个元素,
得到k个元素末尾的指针pre_right和下一组开始的指针cur。

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void reverse(ListNode **head, ListNode **tail) {
if(*head == *tail) return;
if(!*head || !(*head)->next) return;

ListNode *cur = (*head)->next;
ListNode *pre = *head;
ListNode *next;

while(cur != *tail) {
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
cur->next = pre;
*tail = *head;
*head = cur;
}

ListNode *reverseKGroup(ListNode *head, int k) {
if(k == 0) return head;
int n = 0;
ListNode dummy(0);
dummy.next = head;

ListNode *cur = head;
ListNode *left_pre = &dummy;
ListNode *right_pre = &dummy;

while(cur) {
left_pre = right_pre;
ListNode *start = cur;

int i;
for(i = 0; i < k && cur; i++) {
right_pre = cur;
cur = cur->next;
}
if(i != k) break;

reverse(&start, &right_pre);
left_pre->next  = start;
right_pre->next = cur;
}
return dummy.next;
}
};

下面的代码更加漂亮一些:

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void reverse(ListNode **head, ListNode **tail) {
(*tail)->next = NULL;

if(!*head || !(*head)->next) return;

ListNode *cur = (*head)->next;
ListNode *pre = *head;
ListNode *next;

*tail = *head;
while(cur) {
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
*head = pre;
}

ListNode *reverseKGroup(ListNode *head, int k) {
if(k == 0) return head;
int n = 0;
ListNode dummy(0);
dummy.next = head;

ListNode *cur = head;
ListNode *left_pre = &dummy;
ListNode *right_pre = &dummy;

while(cur) {
left_pre = right_pre;
ListNode *start = cur;

int i;
for(i = 0; i < k && cur; i++) {
right_pre = cur;
cur = cur->next;
}
if(i == k) {
reverse(&start, &right_pre);
left_pre->next = start;
right_pre->next = cur;
}
}
return dummy.next;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: