[LeetCode练习题-C语言] 25. Reverse Nodes in k-Group
来源:互联网 发布:日本动画制作软件 编辑:程序博客网 时间:2024/06/17 13:43
[LeetCode练习题-C语言]25. Reverse Nodes in k-Group
题目
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* node = head; struct ListNode* temp; int i; int *valList; while(node != NULL){ temp = node; for(i=0; i<k; i++){ if(node != NULL){ valList[i] = node->val; node = node->next; }else{ k=0; break; } } for(i=0; i<k; i++){ temp->val = valList[k-i-1]; temp = temp->next; } } return head;}
思路
五个节点为一组,将值保存进数组中,然后进行交换。
别人的代码
使用了递归
/** * 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) { auto node = head; for(int i = 0; i < k; ++ i) { if(!node) return head; node = node->next; } auto new_head = reverse(head, node); head->next = reverseKGroup(node, k); return new_head; } ListNode* reverse(ListNode* start, ListNode* end) { ListNode* head = end; while(start != end) { auto temp = start->next; start->next = head; head = start; start = temp; } return head; }};
0 0
- [LeetCode练习题-C语言] 25. Reverse Nodes in k-Group
- 【LeetCode】 25. Reverse Nodes in k-Group C语言
- LeetCode-25-Reverse Nodes in k-Group(C语言实现)
- [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
- [[NSBundle mainBundle]pathForResource:@"name" ofType:@"type"] 获取不到本地文件
- 获取keystore.keystore 签名
- OpenCV (C++ vs Python) vs MATLAB for Computer Vision - OpenCV(C++ 与 Python 的比较)与 MATLAB 的比较
- BZOJ 3555: [Ctsc2014]企鹅QQ
- javascript 问题待解
- [LeetCode练习题-C语言] 25. Reverse Nodes in k-Group
- mysql相关优化
- OPENCV统计比较图像亮度
- 关于eclipse的TestNG的插件安装方法
- ListView的多套布局
- C 语言的编程游戏0801
- 看图吧地图数据如何玩转企业地信圈
- 梯度下降小结
- java的动态代理机制详解