leetcode: Rotate List
来源:互联网 发布:maxwell软件原理 编辑:程序博客网 时间:2024/05/01 14:45
将链表向右移动n个单位。 由于链表向右移动我们每次都要确定新的链表尾部以便下次移动,但是链表尾部是上个尾部的前一节点,在单向的链表中我们只有遍历链表才能获得。这样直接按照题意来做的话循环内每次还要遍历一遍链表,代价是O(n*n),不太合理。
实际上,我们发现如果链表长l,那么向右移动l次链表无变化。如果n<l,那么向右移动n次相当于向左移动l-n次。 而向左移动我们每次需要确定新的头指针,这个指针可以直接利用上个头指针的next来直接获取,比较方便。 因而我们可以吧这道题变成向左移动来做。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode rotateRight(ListNode head, int n) { ListNode st=head; int len=1; if( head==null || n==0 || head.next==null) { return head; } while( st.next!=null ) { len++; st=st.next; } int l=len; while( l<n ) { l+=len; } ListNode tail=st; st = head; for( int i=0;i<l-n;i++ ) { ListNode tmp=st.next; st.next=null; tail.next=st; tail=st; st=tmp; } return st; }}
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
- mysql-5.6.17-win32免安装版配置
- 基于web链接Mysql数据库的细节问题
- android猜猜红桃A游戏源码
- EBS - Flexfield
- 如何搭建独立微信商城
- leetcode: Rotate List
- 激情台球游戏源码
- [转]jgt 32种小家电不合格被责令退市:格兰仕上黑名单
- HDU 4831 Scenic Popularity (线段树)
- Linux下的C语言线程池
- 深入研究 Java Synchronize 和 Lock 的区别与用法
- 程序员永远的痛之字符编码的奥秘
- LINK:fatal error LNK1123: 转换到 COFF 期间失败: 文件无效或损坏
- 仿91助手的PC与android手机通讯(3) --- 检测是否已经安装驱动