[leetcode] 61. Rotate List 解题报告

题目链接:https://leetcode.com/problems/rotate-list/

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.

思路:先找出链表的长度n并记录尾结点为rear,然后再移动(n-k)个结点到要旋转的节点前面结点p,然后将p后面的结点作为头结点,p作为尾结点。需要注意的是一些特殊情况,比如k > n时先对k进行除余。并且如果正好k = n,则不需要旋转。

代码如下:

/**
 * 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) return head;
        ListNode *pHead = new ListNode(0);
        pHead->next = head;
        int n = 0, i = 0;
        ListNode* p = pHead, *rear = NULL;
        while(p->next)//找出链表长度和尾结点
        {
            n++;
            p = p->next;
            if(!p->next) rear = p;
        }
        p = pHead;
        while(i < n-k%n)//走n - k 步到要旋转的结点前
        {
            p = p->next;
            i++;
        }
        if(p == pHead)//如果不需要旋转
        {
            head = pHead->next;
            delete pHead;
            return head;
        }
        rear->next = pHead->next;
        pHead->next = p->next;
        p->next = NULL;
        head = pHead->next;
        delete pHead;
        return head;
    }
};

感觉自己写的有点麻烦,又去看了一下别人怎么写的,发现一种更好的方式。遍历一遍,找出长度n,然后让尾结点连接到头结点,再向前走(n - k%n)步,在从这里断开,下一个节点作为头结点,这个结点作为头结点即可。代码会比之前简洁很多。

代码如下:

/**
 * 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) return head;
        ListNode *p = head, *q;
        int n =1, i =0;
        while(p->next)//找出长度
        {
            n++;
            p = p->next;
        }
        p->next = head;
        while(i < n-k%n)//找到断裂点
        {
            p = p->next;
            i++;
        }
        head = p->next;
        p->next = NULL;
        return head;
    }
};

第二种方法参考:http://fisherlei.blogspot.com/2013/01/leetcode-rotate-list.html

你可能感兴趣的:(LeetCode,链表)