[LeetCode]Rotate List

链表题again. 实现链表节点的循环移位. 注意k的边界范围。

思路:

1. 得到链表长度N,指针end指向尾节点

2. 找到新链表头节点在老链表中的前驱节点,记为p. p = N-k%N-1

3. end指向原链表head节点,此时链表为环状。更新链表头节点位置,head指向p->next。将p->next置为NULL,成为尾节点。

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  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *rotateRight(ListNode *head, int k) {
12         // Note: The Solution object is instantiated only once and is reused by each test case.
13         if(head == NULL || k==0)
14             return head;
15         
16         ListNode *end = head;
17         int N = 1;
18         while(end->next)
19         {
20             ++N;
21             end = end->next;
22         }
23         int p = N-k%N-1;
24         ListNode *pre = head;
25         if(p<0)
26             return head;
27         else
28         {
29             for(int i=0; i<p; ++i)
30                 pre = pre->next;
31             end->next = head;
32             head = pre->next;
33             pre->next = NULL;
34         }
35         return head;
36     }
37 };

 

posted @ 2013-10-25 13:54  Apprentice.Z  阅读(133)  评论(0编辑  收藏  举报