LeetCode:Rotate List
来源:互联网 发布:oppo手机怎么解网络锁 编辑:程序博客网 时间:2024/05/18 13:29
Rotate List
Total Accepted: 66597 Total Submissions: 291807 Difficulty: Medium
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
.
Subscribe to see which companies asked this question
Hide Similar Problems
思路:
1.如给出的例子,找到指向3的指针(p)和指向5的指针(q);
2.将5指向1变成一个环(q->next = head);
3.将4变成新头(head = p->next);
4.将3指向空(p = NULL)。
关键是要求:p、q指针,可以用快、慢指针求,但是由于k可能 > 链表的长度,
因此直接求链表的长度比较方便你。
code:
/** * 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; ListNode *q = head; if(!q || !k) return head; // 求出链表长度 int len = 1; while(q->next){ len++; q = q->next; } q->next = p; // 变成一个环 k %= len; k = len - k; while(--k) p = p->next; // 找到新头结点的前一个结点 head = p->next; p->next = NULL; return head; }};
0 0
- [leetcode][list] Rotate List
- LeetCode: Rotate List
- LeetCode Rotate List
- LeetCode : Rotate List
- [Leetcode] Rotate List
- [LeetCode] Rotate List
- [leetcode] Rotate List
- leetcode 70: Rotate List
- [Leetcode] Rotate List
- 【leetcode】Rotate List
- [LeetCode]Rotate List
- [leetcode]Rotate List
- LeetCode-Rotate List
- [leetcode] Rotate List
- LeetCode - Rotate List
- LeetCode:Rotate List
- LeetCode 61: Rotate List
- leetcode之Rotate List
- 正则表达式- 将div#demo.demo转化成<div id="demo" class="demo"></div>
- 贪心-百度笔试-裁减网格纸
- UVa 140 - Bandwidth
- HTML&CSS——margin:0 auto居中
- 中文分词词性对照表
- LeetCode:Rotate List
- dirname(__file__)函数 返回网站根目录
- SQL使用case判断
- iOS开发者最需要的15个网站
- Android流式布局实现
- 微信接口返回码
- EMC新一代中端存储Unity点评
- struct stat结构体简介
- iOS手势学习笔记