【LeetCode】 Rotate List

来源:互联网 发布:angularjs js cdn 编辑:程序博客网 时间:2024/06/10 05:42

Rotate List

 Total Accepted: 13773 Total Submissions: 62790My Submissions

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)            return head;        if (k <= 0) return head;        int len = 0;        ListNode *p = head, *tail = head;        while (p) {            len++;            tail = p;            p = p->next;        }                k = k % len;        if (k == 0) return head;        int i = 0;        p = head;        while (p) {            i++;            if (i == len - k)                break;            p = p->next;        }        ListNode *tmp_head = p->next;        p->next = NULL;        tail->next = head;        return tmp_head;    }};





0 0