Leetcode-Rotate List

来源:互联网 发布:python能开发界面吗 编辑:程序博客网 时间:2024/06/07 08:12

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:    ListNode* rotateRight(ListNode* head, int k) {        if(head == NULL || head->next == NULL||k==0) return head;                ListNode* node = head;        int size =1;                while(node->next != NULL)        {            size++;            node = node->next;        }                //loop the list        node->next=head;                //handle the case of k>size        k = k%size;                //find the node to break the loop at        while(--size >= k)        {            node=node->next;        }                ListNode* first = node->next;        node->next=NULL;                return first;    }};


原创粉丝点击