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 }
  • 相关阅读:
    Linux查看日志常用命令
    linux(centos)下安装PHP的PDO扩展
    TP thinkphp 权限管理 权限认证 功能
    mysql优化(三)–explain分析sql语句执行效率
    阿里云服务器Centos7成为挖矿肉鸡被挖矿imWBR1耗尽CPU
    Asp.net导入Excel并读取数据
    定义显式类型转换和隐式类型转换
    C# 对象与引用变量
    C# ref参数
    C# 字段与属性的区别
  • 原文地址:https://www.cnblogs.com/Juntaran/p/5511671.html
Copyright © 2011-2022 走看看