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;
        }
    };
  • 相关阅读:
    053-005
    053-002
    053-004
    Dynamic Programming: Fibonacci
    Some tips on using HashSet<T> and List<T>
    使用NPOI导出DataTable到Excel
    简简单单写个特效
    vue项目使用tinymce 适用于5.0版本
    封装AJAX
    全屏滑动效果
  • 原文地址:https://www.cnblogs.com/argenbarbie/p/5267998.html
Copyright © 2011-2022 走看看