LintCode 170-旋转链表
来源:互联网 发布:百度贴吧查ip软件 编辑:程序博客网 时间:2024/06/07 00:56
本人电子系,只为一学生。心喜计算机,小编以怡情。
给定一个链表,旋转链表,使得每个节点向右移动k个位置,其中k是一个非负数
样例
给出链表1->2->3->4->5->null和k=2
返回4->5->1->2->3->null
public ListNode rotateRight(ListNode head, int k) { // write your code here // 给出链表1->2->3->4->5->null和k=2 // 返回4->5->1->2->3->null //先进行特殊值的判断 if(head==null) return null; if(head.next==null) return head; ListNode pre=head; ListNode temp=head; //接下来考虑给的数字大于链表的长度,因此要遍历一遍的到链表长度 int count=1; while(pre.next!=null) { pre=pre.next; count++; } k=k%count; if(k==0) return head;//[1,0] k=100%2==0,就直接返回就好 pre=head;//用完pre别忘指回来 // 给出链表1->2->3->4->5->null和k=2为例 while(k--!=0) { temp=temp.next;//循环两次,temp指向3 } while(temp.next!=null)//然后pre与temp都往后移 { pre=pre.next; temp=temp.next; }//移完后pre指向3,temp指向5 ListNode ret=pre.next;;//设定ret指向4,即旋转完的头指针 temp.next=head;//让5指向1 pre.next=null;//让3指向null return ret;//这样就变成了4 5 1 2 3了 }
0 0
- lintcode-旋转链表-170
- LintCode 170-旋转链表
- lintcode(170)旋转链表
- [Lintcode] #170 旋转链表
- LintCode-旋转链表
- LintCode-旋转链表
- LintCode:旋转链表
- LintCode : 旋转链表
- 旋转链表-LintCode
- [Lintcode]Rotate List旋转链表
- LintCode-旋转图像
- lintcode-旋转图像-161
- LintCode:旋转图像
- LintCode:旋转字符串
- lintcode ----旋转字符串
- LintCode:旋转图像
- Lintcode 恢复旋转数组
- LintCode 8 旋转字符串
- shell脚本创建和kill进程
- ZCMU-1163-分数划分
- Java代理模式
- Chapter 11 Instruction Set: Addressing Modes and Formats
- Longest Substring Without Repeating Characters-LeetCode
- LintCode 170-旋转链表
- 2016这一年
- springboot 使用hibernate进行双向关联json解析时死循环处理
- spring mvc 重定向后还能传递对象数据的方法
- Unity 关于手柄摇杆和键值的测试
- Chapter 12 CPU Structure and Function
- vmware复制虚拟机出现Error:No suitable device found:no device found for connection 'System eth0'
- Chapter 13 Reduced Instruction Set Computer
- pat-a1051. Pop Sequence (25)