[LeetCode] 61. Rotate List Java

题目:

Given a list, rotate the list to the right by k places, where k is non-negative.

Example:

Given 1->2->3->4->5->NULL and k = 2,

return 4->5->1->2->3->NULL.

题意及分析:从右到左第n个点进行翻转链表。主要是要找到翻转点和翻转点前面一个点,然后将最后一个点的next设置为head,翻转点前一个点的next设置为null,返回翻转点即可。

代码:

/**
 * 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 n) {
        if(head == null || n==0) return head;
        int length = 1;     //记录链表有多长
        ListNode p = head;
        while(p.next != null){
            p = p.next;
            length++;
        }
        //此时p指向链表最后一个点
        n=n%length;
        if(n==0) return head;
        ListNode rotedNode = null;
        ListNode preRotate = head;
        int k=0;
        while(k<length-n-1){
            preRotate = preRotate.next;
            k++;
        }
        rotedNode = preRotate.next;

        preRotate.next = null;
        p.next = head;
        return rotedNode;
    }
} 
posted @ 2018-01-10 09:20  荒野第一快递员  阅读(218)  评论(0编辑  收藏  举报