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 }
原文地址:https://www.cnblogs.com/Juntaran/p/5511671.html