[Lintcode] #170 旋转链表

来源:互联网 发布:mmd建模软件 编辑:程序博客网 时间:2024/06/16 00:37

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


样例

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

返回4->5->1->2->3->null

/** * 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)return null;int length = 1;ListNode temp = head;while (temp.next != null) {length++;temp = temp.next;}k %= length;if (k == 0)return head;ListNode fast = head;ListNode slow = head;while (k-- > 0) {fast = fast.next;}while (fast.next != null) {slow = slow.next;fast = fast.next;}ListNode re = slow.next;slow.next = null;temp.next = head;return re;    }}


原创粉丝点击