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

Reverse Nodes in k-Group

2015-06-15 16:44 537 查看
题目:

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个节点的逆转,逆转方式采用头结点插入方式

代码:

struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};

class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if(k<=1||head==NULL || head->next==NULL) return head;
int len=0;
ListNode* p=head;
while(p)//计算总长度
{
len++;
p=p->next;
}
if(k>len) return head;

/*完成k个节点的逆转*/
p=head;
ListNode *pre=p;
ListNode *last=NULL;
ListNode *mark=p;//记录逆转链表的第一个节点,以便将其与后续链表连接起来
p=p->next;
int n=1;
while(n!=k&&p!=NULL)
{
last=p->next;
p->next=pre;
mark->next=last;
pre=p;
p=last;
n++;
}

if(len-k>=k)
mark->next=reverseKGroup(p,k);//递归调用
else
mark->next=p;

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