-
Notifications
You must be signed in to change notification settings - Fork 30
/
RotateList.cs
executable file
·52 lines (48 loc) · 2.77 KB
/
RotateList.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Source : https://leetcode.com/problems/rotate-list/
// Author : codeyu
// Date : Sunday, December 11, 2016 4:10:11 PM
/**********************************************************************************
*
* 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.
*
**********************************************************************************/
using System;
using System.Collections.Generic;
using Algorithms.Utils;
namespace Algorithms
{
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution061
{
public static ListNode RotateRight(ListNode head, int k)
{
if (head == null || k == 0)
return head;
int len = 1;
ListNode p = head;
while (p.next != null) { // 求长度
len++;
p = p.next;
}
k = len - k % len;
p.next = head; // 首尾相连
for(int step = 0; step < k; step++) {
p = p.next; //接着往后跑
}
head = p.next; // 新的首节点
p.next = null; // 断开环
return head;
}
}
}