【leetcode】Rotate List

来源:互联网 发布:彩霸王软件 编辑:程序博客网 时间:2024/06/05 19:00
/** * 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) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if(head==NULL||head->next==NULL||k==0)            return head;                int len=0;        ListNode *ptr=head,*tail=head;        while(ptr!=NULL)        {            len++;            tail=ptr;            ptr=ptr->next;        }                k%=len;                ptr=head;        for(int i=1;i<=len-k-1;i++)        {            ptr=ptr->next;        }                tail->next=head;        head=ptr->next;        ptr->next=NULL;                return head;            }};

原创粉丝点击