• 61. Rotate List


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

    Example 1:

    Input: 1->2->3->4->5->NULL, k = 2
    Output: 4->5->1->2->3->NULL
    Explanation:
    rotate 1 steps to the right: 5->1->2->3->4->NULL
    rotate 2 steps to the right: 4->5->1->2->3->NULL
    

    Example 2:

    Input: 0->1->2->NULL, k = 4
    Output: 2->0->1->NULL
    Explanation:
    rotate 1 steps to the right: 2->0->1->NULL
    rotate 2 steps to the right: 1->2->0->NULL
    rotate 3 steps to the right: 0->1->2->NULL
    rotate 4 steps to the right: 2->0->1->NULL
    /**
     * 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(head == null || k == 0) return head;
            ListNode p = head;
            int length = 1;
            while(p.next != null){
                length++;
                p = p.next;
            }
            k %= length;
            p.next = head;
            int l = length - k;
            ListNode dum = head;
            for(int i = 0; i < l-1; i++){
                dum = dum.next;
            }
            head = dum.next;
            dum.next = null;
            return head;     
        }
    }

    先遍历一遍,得出链表长度len,注意k可能大于len,因此令k %= len。将尾节点next指针指向首节点,形成一个环,接着往后跑len-k步,从这里断开,就是要求的结果了。

    rotate k 步,最后得到的链表最后一个node是第len-k,头节点就是len-k-1.

     
  • 相关阅读:
    字体识别
    TMSHttpConfig工具使用
    firedac分页查询
    filefunc.pas
    dbfunc.pas
    TRawByteStringStream
    大小端交换
    variant的序列和还原
    ansistring和unicode的序列和还原
    malinajs来自Svelte 启发的前端编译器
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11386562.html
Copyright © 2020-2023  润新知