Leetcode——61. Rotate List
来源:互联网 发布:淘宝注册还要拨打号码 编辑:程序博客网 时间:2024/06/16 17:26
题目
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.
解答
One Solution:
/** * 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) { if(head==NULL) return NULL; ListNode *p1=head,*p2=head,*res=head,*callen=head; if(k==0) return head; int len=0; while(callen!=NULL) { callen=callen->next; len++; } int k1=k%len; for(int i=0;i<k1;i++) { p2=p2->next; if(p2==NULL) p2=head; } while(p2->next!=NULL) { p1=p1->next; p2=p2->next; } if(p1->next==NULL) return head; res=p1->next; p1->next=NULL; p2->next=head; return res; }};
Another:
ListNode* rotateRight(ListNode* head, int k) { if (!head || !head->next || k == 0) return head;//nice code!!! ListNode *cur = head; int len = 1; while (cur->next && ++len) cur = cur->next; cur->next = head; k = len - k % len;//clever!!! while (k--) cur = cur->next; head = cur->next; cur->next = nullptr; return head; }
Great description!
https://discuss.leetcode.com/topic/14470/my-clean-c-code-quite-standard-find-tail-and-reconnect-the-list
//本题极易出错!! //本题有个隐含条件,当k值大于list的长度时,需要取模,并根据结果进行翻转,所以一定要先求出链表的长度 //本题两种解法: //解法一:求出链表长度后,更新k,然后利用双指针,一快一慢,找到要分割的点,将链表一分为二。 //注意一个问题,新求出的k如果等于0,代表不需要翻转,直接返回即可 //解法二:在求链表长度时,只需遍历到尾节点,并将尾节点和头结点相连, //剩下的任务只需要一个指针,找到分割的节点,将节点的next置位null,返回节点的原next即可
0 0
- Leetcode——61. Rotate List
- LeetCode——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
- 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
- 1037. 在霍格沃茨找零钱(20)
- codeforces-762A k-th divisor(数学题)
- 1057. 数零壹(20)
- Spring AOP 实现系统操作日志记录
- weex项目实战篇(二)
- Leetcode——61. Rotate List
- Loser,除了努力你还会什么?
- codeforce-762-B USB vs. PS/2(贪心)
- 文章标题
- 【Educational Codeforces Round 17 A题】有所不同的大暴力
- 编程珠玑:第10章 节省空间 10.1 稀疏矩阵表示 ---- 解题总结
- VS2015编译Teamtalk的Windows客户端
- 八、java包与修饰符
- HDU 1272 小希的迷宫