[C语言][LeetCode][61]Rotate List
来源:互联网 发布:115网盘岛国资源 淘宝 编辑:程序博客网 时间:2024/06/01 14:31
题目
Rotate List
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
标签
Linked List、Two Pointers
难度
中等
分析
题目意思是按给定的value旋转单链表。我的做法是先获取链表的长度,然后从头遍历,找到新表的头结点,然后将新表结尾指向到旧表的头。
C代码实现
struct ListNode* rotateRight(struct ListNode* head, int k) { struct ListNode *p, *t, *q, *ret; int length = 0; if(!head) return NULL; p = head; while(p) { p = p->next; length++; } p = head; if(k>length) k = length - k%length; else k = (length-k)%length; while(p && k>1) { q = p; p = p->next; k--; } if(!p->next || k == 0) return head; ret = t = p->next; p->next = NULL; while(t) { q = t; t = t->next; } q->next = head; return ret;}
这里看到别人写的一个更简单的,先找到旧表的尾节点,将尾节点的NEXT指向旧表的头,然后再去遍历找到新表的头结点
struct ListNode* rotateRight(struct ListNode* head, int k) { int i; if(head == NULL || k == 0) { return head; } struct ListNode* p = head; int len = 1; while(p->next != NULL) { p = p->next; len++; } p->next = head; k %= len; for(i = 0; i < len - k; i++) { p = p->next; } head = p->next; p->next = NULL; return head;}
0 0
- [C语言][LeetCode][61]Rotate List
- [leetcode-61]Rotate List(c)
- 【LeetCode】 61. Rotate List C语言
- LeetCode 61: Rotate List
- [leetcode 61] Rotate List
- [leetcode #61]Rotate List
- leetcode || 61、Rotate List
- leetcode[61]:Rotate List
- LeetCode 61: Rotate List
- LeetCode(61) Rotate List
- LeetCode 61 Rotate List
- leetcode 61: Rotate List
- Leetcode#61||Rotate List
- [Leetcode]#61 Rotate List
- leetcode 61:Rotate List
- 【leetcode】【61】Rotate List
- 【LeetCode-61】Rotate List
- LeetCode 61 - Rotate List
- VS 2012 C#ActiveX控件开发总结
- 2015阿里移动推荐算法比赛第一赛季总结
- jsf - javax.validation.ConstraintViolationException
- AP聚类
- Android library引用失败
- [C语言][LeetCode][61]Rotate List
- 如何查看 SQL Server 占用内存
- weblogic忘记管理密码,无法启动服务,重置密码
- linux文件系统inode
- 安卓Banner轮播图效果源码
- 如何创建处理器池之享元模式
- 如何脚本备份各个分库
- java 二叉树遍历
- ThinkPHP if条件下做判断注意的地方。