LeetCode | 61. Rotate List

61. Rotate List

Description

描述:https://leetcode.com/problems/rotate-list/description/
题意:对于给定链表,向右旋转k个位置。

Solution: (Java)
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if (k == 0 || head == null)
            return head;
        ListNode tmp = head, tmp2 = head, ret = null, end = null;
        int len = 0;
        while (tmp != null) {	//遍历一遍统计链表长度,同时确定链表的结尾end
            len++;
            end = tmp;
            tmp = tmp.next;
        }
        k = k % len;		//取余得出实际需要旋转的数
        if (k == 0)
            return head;
        k = len - k;		//实际遍历的终止位置
        int count = 0;
        while (tmp2 != null) {
            count++;
            if (count == k) {
                ret = tmp2.next;
                tmp2.next = null;
                end.next = head;
                break;
            }
            tmp2 = tmp2.next;
        }
        return ret;
    }
}
思路
  • 本题 runtime 0ms,beat 100%;
  • 先遍历一遍统计链表长度,然后第二遍遍历到需要旋转的点,改变链表的结尾和开头即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值