LeetCode Online Judge 题目C# 练习 - 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 public static LinkedListNode RotateList(LinkedListNode head, int k) 2 { 3 if (head == null) 4 return head; 5 6 LinkedListNode p = head; 7 LinkedListNode q = head; 8 9 for (int i = 1; i <= k; i++) 10 { 11 if (p.Next != null) 12 p = p.Next; 13 else 14 p = head; 15 } 16 17 while (p.Next != null) 18 { 19 p = p.Next; 20 q = q.Next; 21 } 22 23 p.Next = head; 24 LinkedListNode ret = q.Next; 25 q.Next = null; 26 27 return ret; 28 }
代码分析:
这题是找倒数第K个节点的varient。