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 
10 static int wing=[]()
11 {
12     std::ios::sync_with_stdio(false);
13     cin.tie(NULL);
14     return 0;
15 }();
16 
17 class Solution 
18 {
19 public:
20     ListNode* rotateRight(ListNode* head, int k) 
21     {
22         int len=0;
23         ListNode *p=head;
24         while(p!=NULL)
25         {
26             p=p->next;
27             len++;
28         }
29         if(len==0)
30             return head;
31         k%=len;
32         if(k==0)
33             return head;
34         ListNode *fast=head,*slow=head;
35         while(k>0)
36         {
37             fast=fast->next;
38             k--;
39         }
40         while(fast->next!=NULL)
41         {
42             slow=slow->next;
43             fast=fast->next;
44         }
45         fast->next=head;
46         fast=slow->next;
47         slow->next=NULL;
48         return fast;
49     }
50 };

循环移动链表元素,关键还是找倒数第k个节点,找到之后,保存下一个节点作为返回值,原末尾节点连在头结点,倒数第k个节点next域置空作为新尾节点。完事儿

posted on 2018-07-19 16:45  高数考了59  阅读(134)  评论(0)    收藏  举报