【LeetCode】Rotate List
来源:互联网 发布:公安局 网络皮条客 编辑:程序博客网 时间:2024/06/05 08:28
Rotate List
Total Accepted: 6485 Total Submissions: 30150 My Submissions
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.
题目大意是将链表右移k个单位,k为非负数。
右移链表,考察的是对链表操作的熟悉度。
注意考虑
1、链表有可能为空;
2、n == 0情况,n >= len情况;
基本思路是,先获取链表前半部分,也就是(len - n),这个在转换之后变为新链表的后半部分。然后处理剩下的链表,这部分会变为新链表的头部。
Total Accepted: 6485 Total Submissions: 30150 My Submissions
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.
题目大意是将链表右移k个单位,k为非负数。
右移链表,考察的是对链表操作的熟悉度。
注意考虑
1、链表有可能为空;
2、n == 0情况,n >= len情况;
基本思路是,先获取链表前半部分,也就是(len - n),这个在转换之后变为新链表的后半部分。然后处理剩下的链表,这部分会变为新链表的头部。
Java AC
/** * 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) { if(n == 0 || head == null){ return head; } int len = 0; ListNode p = head; while(p != null){ p = p.next; len++; } n %= len; if(n == len){ return head; } p = head; ListNode node1 = new ListNode(0); ListNode q = node1; int k = 0; while(k < (len-n)){ q.next = new ListNode(p.val); q = q.next; p = p.next; k++; } ListNode node2 = new ListNode(0); q = node2; while(p != null){ q.next = new ListNode(p.val); q = q.next; p = p.next; } q.next = node1.next; return node2.next; }}
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
- selenium运行自动化脚本(调试验证通过)
- UVa 834 - Continued Fractions
- 开始
- Node.js入门学习笔记-IDE选择/配置之WebStorm(windows)
- Oracle 创建新用户,并授权
- 【LeetCode】Rotate List
- 黑马程序员 java小总结
- Spring JdbcTemplate 批量插入或更新操作
- iOS7.1 企业证书部署无效的问题
- iOS 开发:绘制像素到屏幕
- iOS - Xcode升级到5.1& iOS升级到iOS7.1问题[转]
- APP后期运营小技巧
- js: EXTjs forceFit : true
- IOS视图切换动画效果<代码演示>