170.Rotate List-旋转链表(中等题)

来源:互联网 发布:homebrew安装mysql 编辑:程序博客网 时间:2024/06/05 20:47

旋转链表

  1. 题目

    给定一个链表,旋转链表,使得每个节点向右移动k个位置,其中k是一个非负数

  2. 样例

    给出链表1->2->3->4->5->null和k=2
    返回4->5->1->2->3->null

  3. 题解

先遍历一遍链表,记录长度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