LeetCode OJ 之 Rotate List (链表旋转)
来源:互联网 发布:广州做网络推广的公司 编辑:程序博客网 时间:2024/05/16 12:32
题目:
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
.
思路:
先遍历一遍,得出链表长度l en,注意k 可能大于l en,因此令k% = l en。将尾节点next 指针指向首节点,形成一个环,接着往后跑l en − k 步,从这里断开,就是要求的结果了。
代码1:
/** * 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 || k == 0) return head; ListNode *p1 = head ; int len = 1; while(p1->next) { len++; p1 = p1->next; } k = len - k % len; p1->next = head; for(int i = 0 ; i < k ; i++) { p1 = p1->next;//注意这里是从p1开始向后,需要向后挪动k次,如果从头向后,只需要向后挪动k-1次即可 } head = p1->next; p1->next = NULL; return head; }};
代码2:
/** * 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 || k == 0) return head; ListNode *p1 = head , *p2 = head ; int len = 1; while(p1->next) { len++; p1 = p1->next; } k = len - k % len; for(int i = 0 ; i < k - 1 ; i++) { p2 = p2->next; } p1->next = head; head = p2->next; p2->next = NULL; return head; }};
0 0
- LeetCode OJ 之 Rotate List (链表旋转)
- Rotate List 旋转链表 @LeetCode
- LeetCode(Rotate List) 旋转链表
- LeetCode:Rotate List(旋转链表)
- Leetcode Rotate List 旋转链表
- LeetCode 61. Rotate List(旋转链表)
- Leetcode 61. Rotate List (旋转链表)
- leetcode Rotate list (链表旋转)的python实现
- LeetCode OJ 之 Rotate Image (旋转图像)
- LeetCode OJ:Rotate List
- LeetCode OJ - Rotate List
- LeetCode OJ Rotate List
- Rotate List(链表旋转)
- 61. Rotate List (旋转链表)
- LeetCode-----61. Rotate List(循环旋转链表)
- Rotate List 旋转链表
- 旋转链表---Rotate List
- leetcode解题61. Rotate List java版(旋转链表)
- Erlang入门:构建application练习2
- 未解决问题
- Cocos2dx 3.0 过渡篇(八)浅谈容器Vector
- pt-query-digest查询日志分析工具
- 埃拉托斯特尼(Eratosthene)筛法
- LeetCode OJ 之 Rotate List (链表旋转)
- ubuntu 安装libpostproc52出错。
- 爱干货:Google Play开发者账号注册 最新攻略【2014-01-13】
- Android-小小设置永久解决程序因为未捕获异常而异常终止的问题
- windows inet_ntop inet_pton可参考linux下的实现
- Linux进程间通信——使用信号量
- hashmap简单实例(个人使用经验)
- 单例模式(Singletond)
- Day14-显示图像控件