LeetCode----- 61. Rotate List
来源:互联网 发布:淘宝导航所有分类代码 编辑:程序博客网 时间:2024/06/15 21:35
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为非负数。
解题思路:先判断链表结点个数,然后将单链表构成循环单链表,然后遍历旋转的次数,寻找到头结点。
public class RotateList {public static ListNode rotateRight(ListNode head, int k) {if(head == null || head.next == null) {return head;}int length = 0;ListNode result = new ListNode(0);result.next = head;ListNode node = result;while(node.next!=null) {length++;node = node.next;}node.next = head;//构成循环链表for(int i=0;i<length-k%length;i++) {node = node.next;}result.next = node.next;node.next = null;return result.next; }public static void main(String[] args) {ListNode l10 = new ListNode(1);ListNode l11 = new ListNode(2);ListNode l12 = new ListNode(3);ListNode l13 = new ListNode(4);ListNode l14 = new ListNode(5);ListNode l15 = new ListNode(6);l10.next = l11;l11.next = l12;l12.next = l13;l13.next = l14;l14.next = l15;l15.next = null;ListNode node =rotateRight(l10,7);while(node != null) {if(node.next == null) {System.out.println(node.val);}else{System.out.print(node.val +"->");}node = node.next;}}}
阅读全文
0 0
- [LeetCode]61.Rotate List
- LeetCode --- 61. Rotate List
- [Leetcode] 61. Rotate List
- [leetcode] 61.Rotate List
- [leetcode] 61. Rotate List
- leetcode 61. Rotate List
- LeetCode 61. Rotate List
- [leetcode] 61. Rotate List
- 61. Rotate List LeetCode
- leetcode 61. Rotate List
- LeetCode 61. Rotate List
- leetcode 61. Rotate List
- [LeetCode]61. Rotate List
- LeetCode 61. Rotate List
- LeetCode *** 61. Rotate List
- LeetCode 61. Rotate List
- [Leetcode]61. Rotate List
- LeetCode - 61. Rotate List
- BZOJ 3505: [Cqoi2014]数三角形 计数原理
- UML工具大全(上)
- ubuntu E: 无法获得锁 /var/lib/dpkg/lock
- 【SDK驱动开发3】使用PS侧gpio作为中断输入
- Codeforces Round #406 (Div. 2)
- LeetCode----- 61. Rotate List
- Binary Tree Zigzag Level Order Traversal
- NSWOJ 1156 谁获得了最高奖学金 模拟 NYOJ 60
- IntelliJ IDEA的jsp中request等对象无法被解析的解决办法
- 事务以及JDBC操作事务的学习
- lxml库和贴吧图片下载案例
- 1701H5 范江睿 10月20日 连续第10天总结
- Infinite monkey theorem
- 【Python】使用openCV与dlib实现人脸68特征点的检测与手动修改