Leetcode 61 Rotate List

来源:互联网 发布:网络男歌手到不了 编辑:程序博客网 时间:2024/05/22 10:50

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.

将链表右移K位。

先遍历链表知道链表的长度,移动的位数会出现大于链表长度的情况,所以k=k%cnt

这样只要在cnt-k处断开链表,把后面的部分放在前面部分的前面就得到新的链表了。

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* rotateRight(ListNode* head, int k) {        ListNode* p=head;        if(!p) return p;        int cnt=1,cnt2=1;        while(p->next!=NULL)        {            cnt++;            p=p->next;        }        k%=cnt;        if(k==0) return head;        cnt-=k;        ListNode* q=head;        while(cnt2!=cnt)        {            cnt2++;            q=q->next;        }        p->next=head;        head=q->next;        q->next=NULL;        return head;    }};


1 0