25. Reverse Nodes in k-Group
来源:互联网 发布:俄罗斯聊天软件下载 编辑:程序博客网 时间:2024/06/08 01:56
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked 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 || head->next == NULL || k < 2) return head; ListNode *next_group = head; for (int i = 0; i < k; ++i) { if (next_group) next_group = next_group->next; else return head; } ListNode *new_next_group = reverseKGroup(next_group, k); ListNode *prev = NULL, *cur = head; while (cur != next_group) { ListNode *next = cur->next; cur->next = prev ? prev : new_next_group; prev = cur; cur = next; } return prev; }};
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
- 25. Reverse Nodes in k-Group
- 25. Reverse Nodes in k-Group
- 【LeetCode】25.Reverse Nodes in k-Group
- [leetcode] 25.Reverse Nodes in k-Group
- 25. Reverse Nodes in k-Group
- Leetcode-25.Reverse Nodes in k-Group
- 25. Reverse Nodes in k-Group
- 25. Reverse Nodes in k-Group
- 25. Reverse Nodes in k-Group
- 25. Reverse Nodes in k-Group
- 25. Reverse Nodes in k-Group
- leetcode 25. Reverse Nodes in k-Group
- leetcode 25. Reverse Nodes in k-Group
- 25. Reverse Nodes in k-Group
- Windows Server 2012 R2 会话远程桌面-快速部署
- Zookeeper在Kafka中的应用
- ubuntu安装GitLab
- CTFCrypto练习之RSA算法
- 使用canvas实现行走的小人动画
- 25. Reverse Nodes in k-Group
- git 创建服务端库Shell脚本
- 文章标题
- Android SharePreferences 源码分析
- 刘汝佳的算法竞赛入门经典(第2版) 习题解答
- #循环中的continue 和 break
- zoj2099
- java反射机制
- 简单的js验证码