[Leetcode]Rotate List

来源:互联网 发布:矩阵的秩怎么计算 编辑:程序博客网 时间:2024/06/06 16:40

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.

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    /*algorithm fast slower two pointer    */    ListNode* rotateRight(ListNode* head, int k) {        if(!head || !head->next)return head;        int count = 0;        for(ListNode* p = head;p;p = p->next)++count;        k = k%count;        if(k==0)return head;                ListNode* f = head,*s = f;        //f move k step firstly        while(k--)f = f->next;        while(f->next){            f = f->next;            s = s->next;        }        //f point to last,s point k ahead of end        ListNode* nh = s->next;        s->next = NULL;        f->next = head;        return nh;    }};



0 0
原创粉丝点击