LeetCode:Rotate List

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


原文地址:https://www.cnblogs.com/cynchanpin/p/7352863.html