leetcode:Rotate List
来源:互联网 发布:lab series 知乎 编辑:程序博客网 时间:2024/06/03 17:14
一、 题目
给出一个链表,将右边k个节点移到前面。
例如:1->2->3->4->5->NULL,k = 2时
返回 4->5->1->2->3->NULL
二、 分析
之前我们遇到过将字符右移或左移的,当时的思路是将前一部分反转,后一部分反转,整体再反转,即可得到结果。
不过这道题我们需要换一种思路,其实对于这种链表的问题,我们可以总结出,链表的反转都可以直接从某一个位置开始截断即可,例如上面的这道题:
1、h = head,将指针h移到最后一个非空节点,即5的位置p
2、p->next = head,此时形成了一个环,不过这个环只是我们的工具,我们要找到合适的位置截断
3、继续将指针向前移动len-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) { if(head == NULL || k == 0) return head; int len = 1; ListNode *h; h = head; while(head->next != NULL){ head = head->next; len++; } k = k%len; if(k == 0) return h; else { head->next = h; k = len - k; while(k--){ head = head->next; } h = head->next; head->next = NULL; head = h; } 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
- 网络连接错误提示
- Android基础笔记一
- 编程能力与编程年龄
- 阿拉伯数字转大写金额(支持简体和繁体)
- Java过滤器与SpringMVC拦截器之间的关系与区别
- leetcode:Rotate List
- 搭建eclipse+codesourcery的STM32开发环境
- java ThreadLocal深入解析
- FDHGJNGFJFGJ
- DSFJGHGKLJH.;
- 3.23
- 2015互联网校招总结—一路走来
- 代理模式
- Ruby On Rails 一个提交键传递不同参数到两个post函数