LeetCode-----61. Rotate List(循环旋转链表)

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

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

Subscribe to see which companies asked this question

含义:向右旋转单链表

思路:用一个辅助root结点连接到链表头,先找到要移动的第一个结点的前驱prev,再将prev后的所有结点接到root后面,再将组成一个旋转后的单链表。 

(k的取值,注意为负数或者超出链表长度) 

head.next------指向1

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    private int getLength(ListNode head) {
        int length = 0;
        while (head != null) {
            length ++;
            head = head.next;
        }
        return length;
    }
    public ListNode rotateRight(ListNode head, int n) {
        if(n<=0||head==null){return head;}
        int length = getLength(head);
        n = n % length;
        ListNode dump=new ListNode(0);
        dump.next=head;
        ListNode pre=dump;
        ListNode tail=dump;
        for(int i=0;i<length-n;i++){
            pre=pre.next;//需要反转元素的前一个元素
            tail=tail.next;
        }
        while(tail.next!=null){ tail=tail.next;}//末尾元素
        tail.next=dump.next;
        dump.next=pre.next;
        pre.next=null;
        return dump.next;
    }
}

方案二:

让一个节点先跑n,然后和另一个节点头一起走,就会遇到倒数第k个节点。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值