leetcode 25. Reverse Nodes in k-Group
来源:互联网 发布:白云网络怎么样 编辑:程序博客网 时间:2024/06/06 14:24
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; * struct ListNode *next; * }; */struct ListNode* reverseKGroup(struct ListNode* head, int k) { struct ListNode *pleft,*pmid,*pright,*plast,*pnew,*new_head; int i; if(head==NULL||head->next==NULL||k==1) return head; pnew=head; for(i=1;i<=k-1;i++) //寻找第k个结点,并设为头节点 { pnew=pnew->next; if(pnew==NULL) return head; } new_head=pnew; //第k个为头节点 pleft=head; //left pmid=head->next; //mid plast=head; while(pmid!=NULL) { pright=pmid->next; //pright pmid->next=pleft; //mid指向left if(pmid==pnew) //如果mid是第k个节点 { pmid=pright; //pmid变成pright pnew=pmid; //pnew从当前开始算 plast->next=pnew; //在判断是否还有k个时,先将plast指向当前这个 if(pnew==NULL) //如果后面已经全为空了,那么可以直接输出了 return new_head; for(i=1;i<=k-1;i++) //否则就继续寻找第k个 { pnew=pnew->next; if(pnew==NULL) //如果出现空,则直接返回,不用逆序 return new_head; } //若有k个,则plast指向第k个 plast->next=pnew; //plast一定是指向它 plast=pmid; //重置plast continue; } pleft=pmid; pmid=pright; } return new_head;}
0 0
- [LeetCode]25.Reverse Nodes in k-Group
- LeetCode --- 25. Reverse Nodes in k-Group
- LeetCode 25.Reverse Nodes in k-Group
- [Leetcode] 25. Reverse Nodes in k-Group
- 【LeetCode】25.Reverse Nodes in k-Group
- [leetcode] 25.Reverse Nodes in k-Group
- Leetcode-25.Reverse Nodes in k-Group
- leetcode 25. Reverse Nodes in k-Group
- leetcode 25. Reverse Nodes in k-Group
- leetcode 25. Reverse Nodes in k-Group
- leetcode 25. Reverse Nodes in k-Group
- leetCode 25. Reverse Nodes in k-Group
- Leetcode 25. Reverse Nodes in k-Group
- leetcode:25. Reverse Nodes in k-Group
- LeetCode 25. Reverse Nodes in k-Group
- 【leetcode】25. Reverse Nodes in k-Group
- leetcode 25. Reverse Nodes in k-Group
- leetcode 25. Reverse Nodes in k-Group
- PAT(乙级)1012 D进制的A+B (20)
- ROS Learning-012 beginner_Tutorials (编程) 创建自定义的ROS消息和ROS服务
- ACCESS里导出子窗体内容到指定excel里
- LAB、HSB、RGB和CMYK色彩模式简介
- 远程启动服务
- leetcode 25. Reverse Nodes in k-Group
- 为什么要使用PDO???
- Android Studio导入项目非常慢的解决问题
- python数组基础
- python supervisoe
- 内容提供者总结
- html之储存
- 第二周 项目三--体验复杂度
- 计算输入值的和还有它们的平均值