[LeetCode] 61. Rotate List Java

Posted BrookLearnData

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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;
    }
} 

以上是关于[LeetCode] 61. Rotate List Java的主要内容,如果未能解决你的问题,请参考以下文章

一天一道LeetCode#61. Rotate List

LeetCode 61. Rotate List

Leetcode61 Rotate List

Leetcode 61 -- Rotate List

leetcode61. Rotate List

LeetCode61 Rotate List