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

25. Reverse Nodes in k-Group

2015-06-06 10:05 621 查看
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
/*** 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;int len = 0;ListNode *cur = head;while(cur){++len;cur = cur->next;}//if the length of the list is smaller than k,returnif(len<k)return head;ListNode *dummy = new ListNode(INT_MAX);dummy->next = head;ListNode *prev = dummy;cur = head;ListNode *next = cur->next;//save value of k in a tmp variableint kOrigin = k;//revers the k list nodeswhile(cur && k>0){cur->next = prev;prev = cur;cur = next;if(next)next = next->next;--k;}//set the pointersdummy->next = prev;head->next = NULL;//recurseif(cur)head->next = reverseKGroup(cur,kOrigin);return dummy->next;}};
Swap Nodes in Pairs思路类似,也要用递归,只不过把swap换成了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 || !head->next || k<=1)return head;ListNode *p = head;//计算链表的长度int len = 0;while(p){len++;p = p->next;}//如果k>len,直接返回输入链表if(k > len)return head;p = NULL;ListNode *q = head;int kTmp = k;//将长度为k的链表reversewhile(q && kTmp>0){ListNode *tmp = q->next;q->next = p;p = q;q = tmp;kTmp--;}//如果剩余链表的长度>k,则继续reverseif(len-k >= k)head->next = reverseKGroup(q,k);//否则,将后续链表直接接上elsehead->next = q;return p;}};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: