LeetCode 61. Rotate List

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.

题目意思就是将链表后面k个数,放到链表前面。

那么只需要一次循环就可以确定倒数第k个链表的指针。

  • 用两个指针变量指向头指针
  • 第一个一个指针往后面循环,直到循环了k个数,然后两个指针一块循环;则第一个指针到达尾部时,第二个指针指向的是倒数第k个节点。
  • 然后将最后一个节点的next指向头指针,将第二个指针赋值给头指针,然后将第二个指针赋值为nullptr,这样形成了一个新的链表。
注意:

这组样例:

[1,2]
3

应输出

[2,1]

因此需要先求一个链表长度,然后用k对其取余。

代码如下:

/**
 * 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 == nullptr || k == 0)
            return head;
        
        ListNode *root = head;
        int s = 0;
        while(root)
        {
            s ++;
            root = root->next;
        }
        k %= s;
        if(k == 0)
            return head;
            
        ListNode *left = head, *right = head;
        int res = 0;
        while(right->next)
        {
            if(res >= k)
                left=left->next;
            right=right->next;
            res ++;
        }

        if(res < k)
            return head;

        ListNode *t = left->next;
        left->next = nullptr;
        right->next = head;

        return t;
    }
};
原文地址:https://www.cnblogs.com/aiterator/p/6683442.html