Reverse Nodes in k-Group leetcode
来源:互联网 发布:java图书管理系统报告 编辑:程序博客网 时间:2024/05/01 09:42
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值有关,如上所示, 对于 1->2->3->4->5 当k=2时 2->1->4->3->5
当k=3时 3->2->1->4->5
后面 4 5没变是因为做完一次 3 2 1 剩下的 4 5 已经比k小了,所以保持原来的顺序
思路:
1、先 求出链表总的元素个数temp
2、创建一个头结点result,用来指向result->next=head,并保存头节点reverhead=result;
3、 用temp和k的值比较 while(k<=temp) 当k小于等于temp时就进行逆置操作
4、设置部分逆置长度 ,令 t=k , while(t>0) 进行部分逆置
5、temp=temp-k 最后返回 reverhead->next
代码如下:
/** * 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) { ListNode *p=head,*q,*reverhead; int temp=0; int t; while(p) { ++temp; p=p->next; } if(temp==0||1==k||k>temp) return head; ListNode *result=new ListNode(0);//创建头结点 并用reverhead保存头结点 result->next=head; reverhead=result; p=result->next; //用p来指向下一个节点,进行操作的第一个有效节点 while(k<=temp) //外层循环用k和temp { t=k; //里层循环每次操作t个 ListNode *remark=p; //用remark保存每次进行部分逆置的第一个节点,该节点将指向部分逆置的下一个节点,如上k=2时,1指向3 while(t>0) //将p开始的t个节点进行逆置 { q=p; p=p->next; q->next=result->next; result->next=q; t--; } remark->next=p; //将每部分连接起来 result=remark; //改变result,指向部分逆置的最后一个节点 temp=temp-k; //做了部分逆置后,改变temp } return reverhead->next; }};
- LeetCode:Reverse Nodes in k-Group
- LeetCode: Reverse Nodes in k-Group
- LeetCode : Reverse Nodes in k-Group
- leetcode 42: Reverse Nodes in k-Group
- [Leetcode] reverse nodes in K-Group
- [LeetCode]Reverse Nodes in k-Group
- LeetCode-Reverse Nodes in k-Group
- LeetCode - Reverse Nodes in k-Group
- LeetCode | Reverse Nodes in k-Group
- 【leetcode】Reverse Nodes in k-Group
- Leetcode: Reverse Nodes in k-Group
- leetcode Reverse Nodes in k-Group
- [LeetCode] Reverse Nodes in k-Group
- LeetCode题解: Reverse Nodes in k-Group
- 【Leetcode】Reverse Nodes in k-Group
- LeetCode Reverse Nodes in k-Group
- [Leetcode] Reverse Nodes in k-Group (Java)
- LeetCode(25)Reverse Nodes in K-Group
- 2014/12/15
- 20141215-Amazon Intern F2F Interview Experence
- c++各种类型数据所占字节数
- ldd3源码jiq.c编译出现的问题
- JFreeChart--柱状图
- Reverse Nodes in k-Group leetcode
- Golden32 for oracle 下载,附注册码
- iOS开发快速入门教程——3.1节~3.5节
- 我要做一个什么样的程序员
- 数字图像处理之配置opencv中遇到的问题
- iOS开发快速入门教程——3.6节~3.10节
- const char*, char const*, char*const的区别
- CSS之盒子模型
- Android ListView中 不同的布局实现