LeetCode 题解之Rotate List

1、题目描述

2、题目分析

首先数出链表中的元素个数count,然后对k = k % count 求余数。接着将链表形成一个环,从最后一个元素开始,运动 count - k  步,此时节点的下一个节点就是结果的头节点。

3、代码

 1 ListNode* rotateRight(ListNode* head, int k) {
 2         if( !head || head->next == NULL ){
 3             return head;
 4         }
 5         
 6         int count = 0;
 7         ListNode* p = head ;
 8         while( p != NULL ){
 9             ++count ;
10             p = p->next;
11         }
12         
13         k = k % count ;
14         
15         p = head;
16         while( p->next != NULL ){
17             p = p->next;
18         }
19         
20         p->next = head;
21         int n = count - k ;
22         while( n ){
23             p = p->next ;
24             n--;
25         }
26         
27         ListNode* res = p->next ;
28         p->next = NULL ;
29         return res;
30     }

猜你喜欢

转载自www.cnblogs.com/wangxiaoyong/p/9329952.html