码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode61. Rotate List

时间:2018-09-28 10:52:53      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:style   str   nod   null   init   etc   方法   val   ++   

问题比较简单,方法就是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

标签:style   str   nod   null   init   etc   方法   val   ++   

原文地址:https://www.cnblogs.com/legendcong/p/9716548.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!