1. 程式人生 > >LeetCode:Rotate List

LeetCode:Rotate List

which class primary prim bmi top san rim link

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;
    }
};


LeetCode:Rotate List