• 【LeetCode】61. Rotate List


    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.

    思路如下:将链表首尾相连成环。寻找尾节点的同时可以计算链表长度。

    记链表长度为n,则实际移位次数为k=k%n。记len=n-k。

    也就是说链表的后k个节点成为新链表的前半部分,链表的前len个节点为新链表的后半部分。

    因此head往右第len的节点为新链表的尾,第len+1为新链表的头

    两端相连即可,尾部下一个设为NULL即可。

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode *rotateRight(ListNode *head, int k) {
            if(head == NULL)
                return head;
                
            ListNode* tail = head;
            int n = 1;
            while(tail->next != NULL)
            {
                n ++;
                tail = tail->next;
            }
            k %= n;
            if(k == 0)
                return head;
                
            int len = n-k;
            ListNode* cur = head;
            while(--len)
            {
                cur = cur->next;
            }
            ListNode* post = cur->next;
            cur->next = NULL;
            tail->next = head;
            return post;
        }
    };

  • 相关阅读:
    函数指针的比较
    C++代码
    C++/STL
    Video Downloader使用总结
    98五笔输入法总结
    优酷url的encode与decode
    Directory类总结
    申请GV以及相关
    不用客户端下载腾讯视频
    选择写作博客的原则
  • 原文地址:https://www.cnblogs.com/ganganloveu/p/4155421.html
Copyright © 2020-2023  润新知