码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode] 61. Rotate List Java

时间:2018-01-10 11:24:01      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:leetcode   ota   题目   init   example   ace   nbsp   val   node   

题目:

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   ota   题目   init   example   ace   nbsp   val   node   

原文地址:https://www.cnblogs.com/271934Liao/p/8256891.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!