rotate_list(旋转链表)

题目描述

Given a list, rotate the list to the right by k places, where k is non-negative.
给定一个链表,将链表向右旋转k个位置,其中k是非负的。
For example: Given1->2->3->4->5->NULLand k =2,
return4->5->1->2->3->NULL.

思路:
让链表成环,然后从头结点开始向后面跑length-k,然后从这个部分断开,这样形成的新链表就是旋转之后的链表

注意点:
(1)遍历链表,求出链表的长度length,length应该初始化为1,这样可以防止除0错误
(2)k可能会大于len,因此k = length - k%length;

代码实现:

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
    ListNode *rotateRight(ListNode *head, int k) {
        if (NULL == head)
            return NULL;

        int length = 1;  // 防止发生除0错误
        ListNode* pNode = head;

        while (NULL != pNode->next)
        {
            length++;
            pNode = pNode->next;
        }

        k = length - k%length;

        //将链表连成一个环
        pNode->next = head;
        for (int i = 0; i < k; i++)
        {
            pNode = pNode->next;
        }

        head = pNode->next;
        pNode->next = NULL;
        return head;
    }
};

猜你喜欢

转载自blog.csdn.net/apt1203JN/article/details/81542428