leetcode61. Rotate List

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode61. Rotate List相关的知识,希望对你有一定的参考价值。

问题比较简单,方法就是k%sum,然后移动这么多次,把这段链表插在首部就搞定了。有几个测试用例比较恶心,k==0 head==NULL和k%sum==0的情况,假如k%sum为0的话根本不用任何操作直接返回head就好。

/**
* 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)
            return NULL;
        if (k == 0)
            return head;
        int sum = 0;
        ListNode* st;
        st = head;
        ListNode* dummyNode;
        dummyNode = new ListNode(0);
        dummyNode->next = head;
        while (st != NULL)
        {
            st = st->next;
            sum++;
        }
        if (sum == 1)
            return head;
        if (k > sum)
        {
            k = k%sum;
        }
        int n;
        n = sum - k;
        st = dummyNode;
        while (n--)
        {
            st = st->next;
        }
        if (k==0)
            return head;
        ListNode* p;
        p= st->next;
        st->next = NULL;
        ListNode* q;
        q = p;
        while (q!=NULL&&q->next != NULL)
        {
            q = q->next;
        }
        q->next = dummyNode->next;
        dummyNode->next = p;
        return dummyNode->next;
    }
};

 

以上是关于leetcode61. Rotate List的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode OJ 61. Rotate List 考虑边界条件

一天一道LeetCode#61. Rotate List

LeetCode 61. Rotate List

Leetcode61 Rotate List

Leetcode 61 -- Rotate List

leetcode61. Rotate List