LeetCode Reverse Nodes in k-Group
来源:互联网 发布:用java编写大型游戏 编辑:程序博客网 时间:2024/05/19 04:26
题目:
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 == NULL || k <= 1)return head;int s = 0;ListNode *dummy = new ListNode(-1);ListNode *tail = dummy;ListNode *h1 = head;ListNode *cur = head;while (1) {while (cur != NULL && s != k) {cur = cur->next;s++;}//可以构成一组,对链表进行反转if (s == k) {//下一组的头ListNode *h2 = cur;ListNode *p = h1;ListNode *q = h1->next;while (q != h2) {ListNode *r = q->next;q->next = p;p = q;q = r;}tail->next = p;tail = h1;s = 0;h1 = h2;cur = h2;}else {tail->next = h1;break;}}ListNode *newHead = dummy->next;delete dummy;return newHead;}};
0 0
- 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
- 信息学习16
- 善待自己:改变命运的N个人生哲理
- 在你的灵魂里舞尽我的美丽
- android 工具类 DateUtil
- Calendar 日期工具
- LeetCode Reverse Nodes in k-Group
- input验证(只允许输入字母和数字)
- 一位25岁的董事长给大学生的18条忠告
- 【智能手环APP for Android 】01 百度地图展示行动轨迹
- jdbc链接oracle11g
- JavaScript 类、对象、this指针浅析
- 电脑配置怎么看
- QT表单样式规则
- 全虚拟化和半虚拟化