LeetCode:Rotate List

来源:互联网 发布:oppo手机怎么解网络锁 编辑:程序博客网 时间:2024/05/18 13:29

Rotate List


Total Accepted: 66597 Total Submissions: 291807 Difficulty: Medium

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.

Subscribe to see which companies asked this question

Hide Tags
 Linked List Two Pointers
Hide Similar Problems
 (E) Rotate Array

















思路:

1.如给出的例子,找到指向3的指针(p)和指向5的指针(q);

2.将5指向1变成一个环(q->next = head);

3.将4变成新头(head = p->next);

4.将3指向空(p = NULL)。


关键是要求:p、q指针,可以用快、慢指针求,但是由于k可能 > 链表的长度,

因此直接求链表的长度比较方便你。


code:

/** * 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) {        ListNode *p = head;        ListNode *q = head;        if(!q || !k) return head;                // 求出链表长度        int len = 1;        while(q->next){            len++;            q = q->next;        }        q->next = p; // 变成一个环                k %= len;        k = len - k;        while(--k) p = p->next; // 找到新头结点的前一个结点                head = p->next;        p->next = NULL;        return head;    }};


0 0