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

Leetcode_reverse-nodes-in-k-group

2014-03-23 20:49 369 查看
地址:http://oj.leetcode.com/problems/reverse-nodes-in-k-group/

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

思路:题目里说了只能用常量的额外空间。所以就用一个vector,容量为K,满了K个就反序输出,否则顺序输出。另外注意边界条件,比如k=1或者链表长度小于K的话可以直接输出原链表。
参考代码:

/**
* 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;
if(k<=1)
return head;
vector<ListNode*> vec;
ListNode* p = head, *newHead=NULL, *q=NULL;
while(p)
{
while(p && vec.size()<k)
{
vec.push_back(p);
p = p->next;
}
if(vec.size()==k)
{
if(!newHead)
{
q = newHead = vec.back();
vec.pop_back();
}
while(!vec.empty())
{
q->next = vec.back();
vec.pop_back();
q = q->next;
}
}
else
{
if(!newHead)
{
return head;
}
else
{
for(int i = 0; i < vec.size(); ++i)
{
q->next = vec[i];
q = q->next;
}
}
}
}
q->next = NULL;
return newHead;
}
};

//SECOND TRIAL, without extra spaceclass Solution {public:    ListNode *reverseKGroup(ListNode *head, int k) {        int len = 0;        ListNode* p = head, *pre = NULL, *h = NULL, *nxt = NULL, *lastp = NULL, *curp = NULL;        while(p)        {            ++len;            p = p->next;        }        if(len < k || k<=1)            return head;        p = head;        while(len >= k)        {            len -= k;            curp = p;            for(int i = 0; i<k; ++i)            {                nxt = p->next;                p->next = pre;                pre = p;                p = nxt;            }            if (!h)                h = pre;            else                lastp->next = pre;            lastp = curp;            pre = NULL;        }        if(p)            lastp->next = p;        return h;    }};
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: