zoukankan      html  css  js  c++  java
  • Rotate List —— LeetCode

    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.

    题目大意:给一个链表和一个非负整数k,把链表向右循环移位k位。

    解题思路:踩了个坑,k有可能比链表的长度还长,比如长度为3的链表,k=2000000000,所以开始需要遍历一下链表算出长度,k%=len,然后就是两个pointer一个先走k步,另一个再走,最后把末尾的next节点设为head,新head就是慢指针指向的节点。

    /**
     * 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 k) {
            if(head == null||k == 0){
                return head;
            }
            int fast = k;
            ListNode fastNode = head;
            ListNode slowNode = head;
            ListNode pre = slowNode;
            int len = 0;
            while(fastNode!=null){
                len++;
                fastNode=fastNode.next;
            }
            fast %= len;
            fastNode = head;
            if(fast == 0){
                return head;
            }
            while(fastNode!=null&&fast-->0){
                fastNode = fastNode.next;
            }
            while(fastNode!=null){
                fastNode = fastNode.next;
                pre = slowNode;
                slowNode = slowNode.next;
            }
            ListNode newHead = new ListNode(0);
            newHead.next = slowNode;
            pre.next = null;
            while(slowNode.next!=null){
                slowNode = slowNode.next;
            }
            slowNode.next = head;
            return newHead.next;
        }
    }
  • 相关阅读:
    获取从链接传来的id
    通过域名直接访问Tomcat项目解决方法
    线程与高并发
    阿里云部署javaWeb项目全过程
    前后端分离项目,支持跨域,session不丢失
    python函数
    装饰器
    迭代器和生成器
    C/C++ I/O处理
    C++虚函数
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4516989.html
Copyright © 2011-2022 走看看