[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;
    }
} 

转载于:https://www.cnblogs.com/271934Liao/p/8256891.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值