Leetcode 61 Rotate List
来源:互联网 发布:网络男歌手到不了 编辑:程序博客网 时间:2024/05/22 10:50
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
.
先遍历链表知道链表的长度,移动的位数会出现大于链表长度的情况,所以k=k%cnt
这样只要在cnt-k处断开链表,把后面的部分放在前面部分的前面就得到新的链表了。
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* rotateRight(ListNode* head, int k) { ListNode* p=head; if(!p) return p; int cnt=1,cnt2=1; while(p->next!=NULL) { cnt++; p=p->next; } k%=cnt; if(k==0) return head; cnt-=k; ListNode* q=head; while(cnt2!=cnt) { cnt2++; q=q->next; } p->next=head; head=q->next; q->next=NULL; return head; }};
1 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
- 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-Rotate List-61
- LeetCode 61 Rotate List
- dwz 日期空间onchange事件
- 人脸验证算法Joint Bayesian详解及实现(Python版)
- ASCII
- Java集合浅析
- Hibernate基于Annotation配置(二)
- Leetcode 61 Rotate List
- Mahout Canopy+K-Means
- C语言-运算符优先级
- catalog库配置
- java中自然排序和比较器排序
- 一座楼有10层,兔子可以跳跃的层数可以为1,2或者3,那么兔子到达10层有多少种跳法并列出各种情况。
- ora-12154无法解析指定的连接标识符
- C++ 类模板
- java.lang包学习