Leetcode 61. Rotate List
来源:互联网 发布:excel比对重复数据 编辑:程序博客网 时间:2024/05/18 03:33
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.
s思路:
1. 没什么好说的。需要理解题意,由于往右shift k个位置,k很可能超过List长度。自己做,会默认k
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ //方法1:pointer-to-pointerclass Solution {public: ListNode* rotateRight(ListNode* head, int k) { if(!head) return NULL; ListNode** p=&head,*fast=head; int len=0; while(fast){ fast=fast->next; len++; } int pos=k%len; if(pos==0) return head; fast=head; while(--pos){ fast=fast->next; } while(fast->next){ fast=fast->next; p=&((*p)->next); } fast->next=head; head=(*p); *p=NULL; return head; }};//方法2:简单做法。先扫一遍找到长度,然后把尾巴和开头连起来;//再扫描找到需要改变头节点的位置,因此就不用pointer-to-pointer这些复杂的技能了,因为头节点位置可确定!class Solution {public: ListNode* rotateRight(ListNode* head, int k) { if(!head) return NULL; ListNode* newhead=NULL,*tail=head; int len=1; while(tail->next){ tail=tail->next; len++; } tail->next=head; if(k%=len){ for(int i=0;i<len-k;i++) tail=tail->next; } newhead=tail->next; tail->next=NULL; return newhead; }};
0 0
- [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
- 61. Rotate List LeetCode
- 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
- python 9-4 如何实现属性可修改的函数装饰器,python3 nolocal或者在python2中列表方式
- python 9-5 如何在类中定义装饰器,在包裹函数中就可以持有实例对象,便于修改属性和功能
- Android开发入门——推箱子游戏开发实战(十三)
- eclipse写slorj的艰难开始
- Python学习笔记02_list和tuple
- Leetcode 61. Rotate List
- React&Redux
- Leetcode 62. Unique Paths
- 习题九
- 2048小游戏
- 认识uCOS-II(二)
- 习题十
- 在Ubuntu操作系统中安装基本的开发环境
- mysql 协议的processInfo命令包及解析