zoukankan      html  css  js  c++  java
  • 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.

    1. 

    /**
     * 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 || !k || !head->next)
                return head;
            ListNode *p, *q=head, *r;
            int l=0, i;
            for(p=head; p; p=p->next)
                l++;
            k = k%l;
            for(i=0; i<k; i++)
            {
                if(!q->next)
                    q = head;
                else
                    q = q->next;
            }
            p=head;
            while(q->next)
            {
                p = p->next;
                q = q->next;
            }
            r = p->next;
            if(!r)
                return head;
            p->next = NULL;
            q->next = head;
            return r;
        }
    };

    2.

    先连成环,算长度。

    /**
     * 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 || !k)
                return head;
            ListNode *p, *q=head, *r;
            int l=1, i;
            for(p=head; p->next; p=p->next)
                l++;
            p->next = head;
            k = l-k%l;
            for(i=0; i<k; i++)
                p = p->next;
            head=p->next;
            p->next=NULL;
            return head;
        }
    };
  • 相关阅读:
    C语言-第32课
    typeof和clamp
    C语言void*和*p的使用
    C语言二级指针和一级指针
    C语言结构体变量成员之指针变量成员的坑
    控制硬件三部曲
    C语言const char*使用
    jiffies是什么
    TPO3-1 Architecture
    相关关系|相关系数|线性关系|
  • 原文地址:https://www.cnblogs.com/argenbarbie/p/5267998.html
Copyright © 2011-2022 走看看