【leetcode】61. Rotate List

1. 题目

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.

2. 思路

相隔k的快慢指针。要处理循环右移,因此先将k对链表长度取模。
对长度为0的特殊处理。

3. 代码

耗时:16ms

/**
 * 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 == NULL) {
            return NULL;
        }
        int L = len(head);
        k %= L;
        if (k == 0) { return head; }
        
        ListNode* ph = head;
        ListNode* pt = head;
        while (pt->next != NULL && k > 0) { 
            k--;
            pt = pt->next;
        }
        if (k > 0) { return NULL; }
        while (pt->next != NULL) {
            pt = pt->next;
            ph = ph->next;
        }
        ListNode* new_head = ph->next;
        ph->next = NULL;
        pt->next = head;
        return new_head;
    }
    
    int len(ListNode* head) {
        int l = 0;
        while (head != NULL) {
            l++;
            head = head->next;
        }
        return l;
    }
};
    原文作者:knzeus
    原文地址: https://segmentfault.com/a/1190000007369563
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞