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.

     1 /*************************************************************************
     2     > File Name: LeetCode061.c
     3     > Author: Juntaran
     4     > Mail: JuntaranMail@gmail.com
     5     > Created Time: Tue 17 May 2016 18:47:57 PM CST
     6  ************************************************************************/
     7 
     8 /*************************************************************************
     9     
    10     Rotate List
    11     
    12     Given a list, rotate the list to the right by k places, 
    13     where k is non-negative.
    14 
    15     For example:
    16     Given 1->2->3->4->5->NULL and k = 2,
    17     return 4->5->1->2->3->NULL.
    18 
    19  ************************************************************************/
    20  
    21 #include <stdio.h>
    22 /**
    23  * Definition for singly-linked list.
    24  * struct ListNode {
    25  *     int val;
    26  *     struct ListNode *next;
    27  * };
    28  */
    29 struct ListNode* rotateRight(struct ListNode* head, int k) 
    30 {
    31     struct ListNode* fast = head;
    32     struct ListNode* slow = head;
    33     struct ListNode* newhead = head;
    34     int length = 1;
    35     
    36     if( head == NULL || k < 0 )
    37     {
    38         return head;
    39     }
    40     
    41     while( fast->next != NULL )
    42     {
    43         fast = fast->next;
    44         length ++;
    45     }
    46     fast = head;
    47     k = k % length;
    48 //  printf("%d %d
    ",k,length);
    49     
    50     while( k > 0 )
    51     {
    52         fast = fast->next;
    53         if( fast == NULL )
    54         {
    55             return head;
    56         }
    57         k --;
    58     }
    59     
    60     while( fast->next != NULL )
    61     {
    62         slow = slow->next;
    63         fast = fast->next;
    64     }
    65     fast->next = head;
    66     newhead = slow->next;
    67     slow->next = NULL;
    68     
    69     return newhead;
    70 }
  • 相关阅读:
    [NOI2009]管道取珠 DP + 递推
    poj3207 Ikki's Story IV
    NOIP2016Day1T2天天爱跑步(LCA+桶)
    NOIP2016Day2T3愤怒的小鸟(状压dp) O(2^n*n^2)再优化
    NOIP2016Day1T3换教室(floyd+期望dp)
    bzoj1854: [Scoi2010]游戏(匈牙利) / GDKOI Day2 T2(最大流)
    [CodeVs4927]线段树练习5
    基数排序的奇技淫巧
    bzoj2724: [Violet 6]蒲公英(离散化+分块)
    bzoj1483: [HNOI2009]梦幻布丁(链表+启发式合并)
  • 原文地址:https://www.cnblogs.com/Juntaran/p/5511671.html
Copyright © 2011-2022 走看看