Rotate List

来源:互联网 发布:scientific linux 6 编辑:程序博客网 时间:2024/06/05 04:21


/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode rotateRight(ListNode head, int k) {        if (head == null) {            return null;        }        int length = 1;        ListNode dummy = new ListNode(-1);        dummy.next = head;        while (head.next != null) {            head = head.next;            length++;        }        int shift = k % length;        if (shift <= 0) {            return dummy.next;        }        ListNode ptr = dummy;        for (int i = 0; i < (length - shift); i++) {            ptr = ptr.next;        }        head.next = dummy.next;        dummy.next = ptr.next;        ptr.next = null;        return dummy.next;    }}


0 0
原创粉丝点击