170.Rotate List-旋转链表(中等题)
来源:互联网 发布:homebrew安装mysql 编辑:程序博客网 时间:2024/06/05 20:47
旋转链表
题目
给定一个链表,旋转链表,使得每个节点向右移动k个位置,其中k是一个非负数
样例
给出链表1->2->3->4->5->null和k=2
返回4->5->1->2->3->null题解
先遍历一遍链表,记录长度count,再将k对count取模以降低由于k>count带来的冗余的时间复杂度。最后再遍历一次链表,当遍历至count-k时截断链表,获得新链表的头尾节点,再组合成新的完整链表即可。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { /** * @param head: the List * @param k: rotate to the right k places * @return: the list after rotation */ public ListNode rotateRight(ListNode head, int k) { // write your code here if (head == null || head.next == null) { return head; } int count = 0; ListNode temp = head; ListNode tail = null; ListNode newHead = null; while (temp != null) { count++; if (temp.next == null) { tail = temp; } temp = temp.next; } if (k % count == 0) { return head; } if (k > count) { k=k%count; } temp = head; int i = 1; while (temp != null) { if (i == count-k) { newHead = temp.next; temp.next = null; tail.next = head; break; } i++; temp = temp.next; } return newHead; }}
Last Update 2016.10.24
0 0
- 170.Rotate List-旋转链表(中等题)
- Rotate List(链表旋转)
- 61. Rotate List (旋转链表)
- Rotate List 旋转链表
- 旋转链表---Rotate List
- 161.Rotate Image-旋转图像(中等题)
- LeetCode OJ 之 Rotate List (链表旋转)
- LeetCode 61. Rotate List(旋转链表)
- Leetcode 61. Rotate List (旋转链表)
- leetcode Rotate list (链表旋转)的python实现
- Rotate List 旋转链表 @LeetCode
- LeetCode(Rotate List) 旋转链表
- LeetCode:Rotate List(旋转链表)
- Leetcode Rotate List 旋转链表
- Rotate List 部分旋转链表
- [Lintcode]Rotate List旋转链表
- 102.Linked List Cycle-带环链表(中等题)
- 99.Reorder List-重排链表(中等题)
- Oracle 11g学习笔记--审计
- Ubuntu 16.04 LTS安装sogou输入法详解
- 关于版本控制软件以及Git的简单介绍
- php将xml变成array
- ECMAScript6笔记:ECMAScript6简介
- 170.Rotate List-旋转链表(中等题)
- 多文件中共享变量
- Unity 使用Profile查看真机性能
- ArrayList
- mysql 字段类型
- 数据结构与算法分析_数组的子序列问题
- 《 JavaScript&jQuery交互式Web前端开发》读书笔记二:各种页面加载事件的区别
- 网页设计中常用字体
- MAC ReactNative环境搭建