Rotate List

来源:互联网 发布:猪脸识别 知乎 编辑:程序博客网 时间:2024/06/05 07:03

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.


先遍历找到size,首尾相连,然后移动 size - k%size -1这么多步,再断开。


public ListNode rotateRight(ListNode head, int k) {        if(head == null) return null;                int size = 0;        ListNode p = new ListNode(-1);        p.next = head;        while(p.next != null){            size++;            p = p.next;        }        System.out.println("size:"+size);        int move = size - k % size-1;        p.next = head;        p = head;        for(int i=0;i<move;i++){            p = p.next;        }        ListNode result = p.next;        p.next = null;        return result;    }


0 0