链表的旋转

题目:

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:
Given1->2->3->4->5->NULLand k =2,
return4->5->1->2->3->NULL.


解题思路:

观察发现,如果我们将元素收尾相连,然后将头结点的指针向右移动k个位置,再将链表断开就得到了我们想要的结果。


代码实现:

class Solution {
public:
    ListNode *rotateRight(ListNode *head, int k) {
        if(head == NULL)
            return NULL;
        if(k < 0)
            return head;
        //count为链表中结点个数
        int count = 1;
        ListNode* cur = head;
        while(cur->next != NULL)
        {
            count++;
            cur = cur->next;
        }
        k %= count;
        //现将链表连成一个环,然后将head向后走count-k步,将环断开
        cur->next = head;
        int step = count - k;
        ListNode* pre = head;
        while(step--)
        {
            pre = head;
            head = head->next;
        }
        pre->next = NULL;
        return head;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_40417029/article/details/80975201