[leetCode]旋转链表的k个节点

旋转链表的k个节点可以使用快慢指针来解决。

测试用例当时没有跑过,后来仔细想想,没有考虑到一点就是参数k在后台可能是给的很大,远远大于count的时候,整个链表就会旋转的特别乱,所以需要将k控制到count的范围内。

在线OJ的代码如下:

class Solution {
public:
    ListNode *rotateRight(ListNode *head, int k) {
        int count = 0;
        //判断是否为空
         if(head==NULL)
        {
            return NULL;
        }
        ListNode* node = head;
        //统计该链表有多少个节点
        while(node)
        {
            count++;
            node = node->next;
        }
        k %= count;
        ListNode *fast = head, *slow = head; 
        for (int i = 0; i < k; ++i) {
            if (fast)
                 fast = fast->next;
        }
        if (!fast)
            return head;
        while (fast->next) {
            fast = fast->next;
            slow = slow->next;
        }
        fast->next = head;
        fast = slow->next;
        slow->next = NULL;
        return fast;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_36474990/article/details/80634047