Reverse Nodes in k-Group
来源:互联网 发布:linux如何查看内核日志 编辑:程序博客网 时间:2024/06/06 07:30
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 || k <=1){ return head; } ListNode dummy(0); dummy.next = head; ListNode * front = &dummy; ListNode * end = NULL; while(front){ end = front; for(int i = 0; i < k; i++){ end = end->next; if(!end){ return dummy.next; } } front = reverse(front, end->next); } return dummy.next; } //对(front, end)左右开区间的链表元素进行逆序 ListNode * reverse(ListNode * front, ListNode * end){ ListNode * pre = front; ListNode * cur = pre->next; while(cur->next != end){ ListNode * suc = cur->next; cur->next = suc->next; suc->next = pre->next; pre->next = suc; } //注意应该返回逆序后的最后一个节点作为下一个group的前驱节点 return cur; }};
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
- u-boot.lds文件诠释
- 如何右键新建HTML
- 我理解的设计模式:单例模式
- 人工智能中对机器学非常简要的介绍
- 模板-KM算法
- Reverse Nodes in k-Group
- Windows Server 2012 如何将软件加入开机自启项
- 第一个内核测试程序
- error LNK2005: __pRawDllMain already defined in UiPlugin.obj
- Centos安装MySQL数据库遇到的问题总结
- 如何在HTML页面中保留空格和换行符
- POJ 2947 高斯消元
- Android——文本类控件
- Mac或Windows下安装MyEclipse2015