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->5For k = 2, you should return:
2->1->4->3->5For 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;}};
相关文章推荐
- openstack--计算节点安装(Node)
- Swap Nodes in Pairs
- LeetCode "Count Complete Tree Nodes"
- leetcode 222: Count Complete Tree Nodes
- 翻译 - NodeJS错误处理最佳实践
- LeetCode题解(19)--Remove Nth Node From End of List
- Setup node.js on Windows Server
- 5.1.10 Populating Next Right Pointers in Each Node II
- node-glob学习
- 用NODEJS处理EXCEL文件导入导出,文件上传
- iOS 用GDataXMLNode创建和解析XML
- LeetCode_19---Remove Nth Node From End of List
- 【NodeJS】---express配置ejs mongoose route等
- nodejs安装及环境配置
- leetcode 19 -- Remove Nth Node From End of List
- nodePPT 这可能是迄今为止最好的网页版PPT
- NodeJs安装教程
- 用 node 实现仿微信风格的 token 获取接口
- Node.js 学习资源总结
- Use Node.js DDP Client on Arduino Yun to Access Meteor Server