Reverse Nodes in k-Group
来源:互联网 发布:刘德华谁人知国语版 编辑:程序博客网 时间:2024/06/05 20: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个节点的函数,每次转换k个。注意转换函数中,由头到尾转换时候pEnd以及pHead顺序的变换。
代码:
class Solution {//https://leetcode.com/problems/reverse-nodes-in-k-group/public: ListNode* reverseKGroup(ListNode* head, int k) { if(k<=0||head==NULL) return head; ListNode *dummy=new ListNode(0);dummy->next=head; ListNode *p=dummy; while(p){ p->next=reverseList(p->next,k); for(int i=1;p&&i<=k;i++){ p=p->next; } } return dummy->next; } ListNode* reverseList(ListNode* head,int k){ if(k<=0) return head; ListNode* pEnd=head; while(pEnd&&k){ pEnd=pEnd->next; k--; } if(k>0) return head; ListNode *pHead=pEnd,*p=head; while(p!=pEnd){ ListNode *q=p->next;//有一个好处就是pHead指向空的,自动的了,不想之前需要考虑这个问题,直接从头部指向最后一个 p->next=pHead; pHead=p; p=q;//从后面往前 } return pHead;//连续,后面不断开 }};
0 0
- Reverse Nodes in k-Group
- Reverse Nodes in K-Group
- Reverse Nodes in k-Group
- Reverse Nodes In K Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- Reverse Nodes in k-Group
- 系统目录介绍
- Java NIO框架Netty教程(一) – Hello Netty
- spring 定时器 详细配置
- Unity3D 串口通信 遇到的问题记录
- tableViewCell自适应高度
- Reverse Nodes in k-Group
- Lua源码分析——C文件说明
- 在Ubuntu安装go编译环境
- C语言的声明与定义
- 最短路径(Dijkstra)
- Java-构建器模式(Buider模式)
- select…start with…connect by…prior ORDER SIBLINGS BY
- Java集合基础知识
- OpenGL线性渐变色绘制