61. Rotate List
来源:互联网 发布:阿里云邮箱人工客服 编辑:程序博客网 时间:2024/06/08 06:16
1、题目描述
给一个单链表和整数k,旋转链表k位,返回新链表。
2、思路
也就是说,把链表的倒数k位,全都移动到链表头上来,
k可能会大于链表长度,所以实际移动步数是k%len。
Two Pointers。
一个指针f先走k步,之后指针p和f一起走,直到f走到最后一个节点。
此时p的位置是新链表的尾元素位置。
让f->next等于head,让 答案指向p->next,让p->next = NULL。
3、代码
ListNode* rotateRight(ListNode* head, int k) { ListNode* f=head; if(f==NULL) return head; int len=0; while(f){ len++; f=f->next; } k=k%len; f=head; for(int i=0;i<k;i++){ f=f->next; } ListNode* p=head; while(f->next){ p=p->next; f=f->next; } f->next = head; head = p->next; p->next=NULL; return head; }
阅读全文
0 0
- [LeetCode]61.Rotate List
- 61. Rotate List
- LeetCode --- 61. Rotate List
- [Leetcode] 61. Rotate List
- 61. Rotate List
- [leetcode] 61.Rotate List
- [leetcode] 61. Rotate List
- 61. Rotate List
- leetcode 61. Rotate List
- LeetCode 61. Rotate List
- [leetcode] 61. Rotate List
- 61. Rotate List
- 61. Rotate List
- 61. Rotate List LeetCode
- leetcode 61. Rotate List
- 61. Rotate List
- 61. Rotate List
- 61. Rotate List
- 前端开发规范:命名规范、html规范、css规范、js规范
- spring 实现定时任务demo
- 人物IK设置(改变左右手角度实现拿东西效果)
- 练习:关于通讯录管理系统
- 人工智能工程师学习路线及具备的5项基本技能
- 61. Rotate List
- Hibernate单表操作
- Hadoop YARN 内存和CPU两种资源的调度
- +=
- darwin之数据包管理
- 深入浅出K-Means算法
- Android常见的内存溢出OOM
- My Shopping
- jdbc连接mysql数据库简单代码