[leetcode-25]Reverse Nodes in k-Group(C)
来源:互联网 发布:塞尔维亚 知乎 编辑:程序博客网 时间:2024/04/29 15:55
问题描述:
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
分析:这道题列为hard,我觉得还是蛮奇怪的。这道题就是将一个链表以k为组进行分割,然后在每个组里进行调转。
代码如下:12ms
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */struct ListNode* reverseGroup(struct ListNode* head,int k,struct ListNode** nextHead){ int i; struct ListNode *prev = NULL,*current=head,*next; for(i = 0;i<k;i++){ next = current->next; current->next = prev; prev = current; current = next; } *nextHead = current; return prev;}struct ListNode* reverseKGroup(struct ListNode* head, int k) { int length = 0; struct ListNode *currentHead = head; struct ListNode *nextHead = NULL; struct ListNode *tail = NULL; struct ListNode *tmpHead = head; while(tmpHead){ length++; tmpHead = tmpHead->next; } int i; if(length<k) return head; if(k==1) return head; for(i = k-1;i<length;i=i+k){ tmpHead = reverseGroup(currentHead,k,&nextHead); if(!tail){//第一组 head = tmpHead; tail = currentHead; } else{ tail->next = tmpHead; tail = currentHead; } currentHead = nextHead; } tail->next = currentHead; return head;}
0 0
- [leetcode-25]Reverse Nodes in k-Group(C)
- 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
- python将txt转换为csv
- 全文检索的基本原理之Lucene原理篇
- 三向切分的快速排序
- 一步步优化JVM<三>:GC优化基础
- PHP的json_encode函数应用到微信接口问题(include \uxxxx will create fail)
- [leetcode-25]Reverse Nodes in k-Group(C)
- http://blog.sina.com.cn/s/blog_4c0e8aa20100ung8.html
- Android 简易文件选择Dialog
- Android Studio 里面 导入SlidingMenu
- 网络远程教育实施方案交流之(三)——服务器架构及视频存储方案
- 数据仓库基础知识~
- zoj3885最小费用最大流
- 报表与微信公众号(企业号)集成方案
- 1,2报数最后剩下的人的问题