LeetCode-Rotate List

来源:互联网 发布:gif动态图片编辑软件 编辑:程序博客网 时间:2024/04/20 13:19

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.

Solution:

Code:

<span style="font-size:14px;">/** * 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) return head;        int length = 0;        ListNode *copy = head, *temp;        while (copy != NULL) {            length++;            copy = copy->next;        }        k = k%length;        if (k == 0) return head;        copy = head;        for (int i = 0; i < length-k-1; ++i)            copy = copy->next;        temp = copy->next;        copy->next = NULL;        copy = temp;        while (copy != NULL && copy->next != NULL)            copy = copy->next;        copy->next = head;        return temp;    }};</span>



0 0
原创粉丝点击