zoukankan      html  css  js  c++  java
  • leetcode61 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 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode* rotateRight(ListNode* head, int k) {
    12         ListNode *ans=NULL;
    13         
    14         int size=0;
    15         ListNode *p=head;
    16         while(p)
    17         {
    18             size++;
    19             p=p->next;
    20         }
    21         if(size==0)
    22             return ans;
    23         
    24         k=k%size;
    25         
    26         if(k==0)
    27             return head;
    28         
    29         int t=size-k;
    30         p=head;
    31         while(--t)
    32         {
    33             p=p->next;
    34         }
    35         ListNode*pp=p->next;
    36         p->next=NULL;
    37         ans=pp;
    38         while(pp->next!=NULL)
    39         {
    40             pp=pp->next;
    41         }
    42         pp->next=head;
    43         return ans;
    44         
    45     }
    46     
    47 };
    View Code
  • 相关阅读:
    Blocks to Cubes
    poj1113凸包
    AtCoder Regular Contest 078D
    Codeforces Round #400
    hdu2196树形dp
    Codeforces Round #409
    Codeforces Round #424
    hdu1520树形dp第一题
    Codeforces Round #412
    poj2823单调队列
  • 原文地址:https://www.cnblogs.com/jsir2016bky/p/5105873.html
Copyright © 2011-2022 走看看