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

    /**
     * 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||head->next==NULL||k==0)
            return head;
        ListNode *pre0=head ,*pre1, *pre2;
        int len=0;
        while (pre0)
        {
            len++;
            pre1=pre0;
            pre0=pre0->next;
        }
        k%=len;
        if(k==0)return head;
        ListNode  *headNew;
        pre2=head;
        for(int i=0;i<len-k-1;i++)
        {
            pre2=pre2->next;
        }
        headNew=pre2->next;
        pre2->next=NULL;
        pre1->next=head;
        return headNew;
    }
    /**
    ListNode *rotateRight(ListNode *head, int k) 
    {
        if(head==NULL||head->next==NULL||k==0)
            return head;
        ListNode *pre0=head;
        int len=0;
        while (pre0)
        {
            len++;
            pre0=pre0->next;
        }
        k%=len;
        if(k==0)return head;
        ListNode *pre1=head, *cur, *headNew;
        int icount=0;
        while(pre1)
        {
            icount++;
            pre1=pre1->next;
            if (icount==k)
            {        
                cur=head;
                while(pre1->next)
                {
                    pre1=pre1->next;
                    cur=cur->next;
                }
                headNew=cur->next;            
                cur->next=NULL;
                pre1->next=head;    
                return headNew;
            }
        }
    }
    */
    };
  • 相关阅读:
    归并排序
    快速排序
    冒泡排序
    排序算法复杂度
    [LeetCode] 20. Valid Parentheses ☆(括号匹配问题)
    makefile编写helloworld
    shell的通俗理解
    PID三种参数的理解
    PID的原理
    PID控制温度
  • 原文地址:https://www.cnblogs.com/Vae1990Silence/p/4281514.html
Copyright © 2011-2022 走看看