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

LeetCode: Reverse Nodes in k-Group

2013-04-20 13:06 471 查看
从这题和上一题可以总结出反转链表的经验,需要有5个指针:end, q, p, pPre, pNext. p和pPre进行方向转置后p和pPre向后移,pNext用来记录转置前p的后一个,q用来记录转置串之前的node,end记录转置串最开始的node。

/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ListNode *pPre, *end, *p, *q;
p = head;
q = NULL;
bool flag = true;
while (flag) {
end = pPre = p;
ListNode *tmp = pPre;
for (int i = 0; i < k; i++) {
if (tmp) tmp = tmp->next;
else {
flag = false;
break;
}
}
if (!flag) break;
p = p->next;
for (int i = 0; i < k-1; i++) {
ListNode *pNext = p->next;
p->next = pPre;
pPre = p;
p = pNext;
}
end->next = p;
if (!q) head = pPre;
else q->next = pPre;
q = end;
}
return head;
}
};


recursive的方法更好理解

/**
* 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) return NULL;
ListNode *p = head;
int len = 0;
for (; p && len < k; p = p->next) len++;
if (len < k) return head;
ListNode *pre = NULL;
p = head;
for (int i = 0; i < k; ++i) {
ListNode *pnext = p->next;
p->next = pre;
pre = p;
p = pnext;
}
head->next = reverseKGroup(p, k);
return pre;
}
};


C#

/**
* Definition for singly-linked list.
* public class ListNode {
*     public int val;
*     public ListNode next;
*     public ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode ReverseKGroup(ListNode head, int k) {
if (head == null) return null;
ListNode p = head;
int len = 0;
for (; p != null && len < k; p = p.next) len++;
if (len < k) return head;
ListNode pre = null;
p = head;
for (int i = 0; i < k; i++) {
ListNode pNext = p.next;
p.next = pre;
pre = p;
p = pNext;
}
head.next = ReverseKGroup(p, k);
return pre;
}
}


View Code
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: