文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Leetcode 61. Rotate List

2. Solution

/**
 * 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) {
            return head;
        }
        int n = 0;
        ListNode* pre = nullptr;
        ListNode* current = head;
        while(current) {
            n++;
            pre = current;
            current = current->next; 
        }
        pre->next = head;
        int target = n - k % n;
        current = head;
        while(target) {
            target--;
            pre = current;
            current = current->next;
        }
        pre->next = nullptr;
        return current;
    }
};

Reference

  1. https://leetcode.com/problems/rotate-list/description/

相关文章:

  • 2022-01-20
  • 2022-02-21
  • 2022-12-23
  • 2021-05-03
  • 2021-07-17
猜你喜欢
  • 2021-10-10
  • 2021-08-02
  • 2021-11-16
  • 2021-06-27
  • 2021-06-04
  • 2022-03-03
  • 2021-10-22
相关资源
相似解决方案