LeetCode61——Rotate List

来源:互联网 发布:珠江新闻眼回看软件 编辑:程序博客网 时间:2024/06/05 20:31

LeetCode61——Rotate List

简单的链表操作。维护head和r指针,r初始指向链表末尾,并且r-next=head;

首尾相接,再根据给定K移动特定指针。

比如说,链表长度len=5,那么当k为1时,head指针向后移动len-k=4步,而r指针也移动同样步骤,这样始终有r->next==head;


最后将循环链表拆开为单链表即可。

注:根据提交经验,k会给很大,这时我们让k对链表长度取模即可。

代码:

class Solution {public:ListNode* rotateRight(ListNode* head, int k) {if (k == 0 || head == NULL)return head;ListNode*r = head;int count = 1;while (r->next){count++;//链表长度r = r->next;}k = k%count;//处理kif (k==0){return head;}r->next = head;//循环链表int move = count - k;while (move--){head = head->next;r = r->next;}r->next = NULL;//拆开return head;}};


后记:

今天做了11题,累坏了。。。写完博客洗洗睡了、、

0 0
原创粉丝点击