LeetCode61 Rotate List 旋转链表

问题描述:
Given a linked list, rotate the list to the right by k places, where k is non-negative.

Example 1:

Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL

Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL
Example 2:

Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL

Explanation:
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL
题源:here;完整实现:here
思路:
假设输入链表长度为listLen,因为旋转周期为listLen,所以k = k%listLen。向右旋转k次等价于将后k个数挪到链表前端。思路相同,实现有两种:1 用两个链表分别记录k前后的链表;2 形成循环链表后拆开。受到python的影响,最近在实践python风格的C++代码,确实会简洁许多。人生苦短,我用python。
实现1:两链表

    ListNode* rotateRight(ListNode* head, int k) {
        if (!head) return NULL;
        ListNode *left = NULL, *right = NULL, *leftCurr = NULL, *rightCurr = NULL;
        int count = 0; ListNode *curr = head; int listLen = 0;
        while (curr){
            listLen++; curr = curr->next;}

        curr = head; k = k % listLen;
        while (curr){
            if (count < listLen-k){
                if (!left){
                    left = new ListNode(curr->val); leftCurr = left;
                }else{
                    leftCurr->next = new ListNode(curr->val);
                    leftCurr = leftCurr->next;}
            }else{
                if (!right){
                    right = new ListNode(curr->val); rightCurr = right;
                }else{
                    rightCurr->next = new ListNode(curr->val);
                    rightCurr = rightCurr->next;}}
            curr = curr->next; count++;}

        if (right){
            rightCurr->next = left; return right;}
        else return left;}

实现2:循环链表

    ListNode* rotateRight_2(ListNode* head, int k){
        if (!head || k<=0) return head;
        ListNode *p = head; int listLen = 1;
        while (p->next){
            listLen++; p = p->next;}

        p->next = head; k = listLen - k%listLen;
        while (k > 0) { 
            p = p->next; k--;}

        head = p->next; p->next = NULL;

        return head;}

猜你喜欢

转载自blog.csdn.net/m0_37518259/article/details/80919538