Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Rotate List - หมุน Linked List ไปทางขวา k ตำแหน่งใน C++


ภาพรวมปัญหา

มี Linked List ต้องหมุนไปทางขวา k ตำแหน่ง (k ≥ 0)

ตัวอย่าง: [1,2,3,4,5], k=2 → [4,5,1,2,3]

อัลกอริทึม

  1. ถ้าลิสต์ว่าง → return null
  2. นับความยาว len, หา tail node
  3. เชื่อม tail->next = head (ทำให้เป็นวงกลม)
  4. k = k % len
  5. เดินจาก head ไป len-k ก้าว → ตำแหน่งก่อน head ใหม่
  6. newHead = tail->next, tail->next = NULL
  7. return newHead

ตัวอย่างโค้ด C++

#include <bits/stdc++.h>
using namespace std;

class ListNode{
public:
    int val;
    ListNode *next;
    ListNode(int data){ val = data; next = NULL; }
};

ListNode *make_list(vector<int> v){
    ListNode *head = new ListNode(v[0]);
    for(int i = 1; i < v.size(); i++){
        ListNode *ptr = head;
        while(ptr->next != NULL) ptr = ptr->next;
        ptr->next = new ListNode(v[i]);
    }
    return head;
}

void print_list(ListNode *head){
    ListNode *ptr = head;
    cout << "[";
    while(ptr->next){ cout << ptr->val << ", "; ptr = ptr->next; }
    cout << "]" << endl;
}

class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if(!head) return head;
        int len = 1;
        ListNode* tail = head;
        while(tail->next){ len++; tail = tail->next; }
        tail->next = head;
        k %= len;
        ListNode* newHead = NULL;
        for(int i = 0; i < len - k; i++) tail = tail->next;
        newHead = tail->next;
        tail->next = NULL;
        return newHead;
    }
};

int main(){
    Solution ob;
    vector<int> v = {1,2,3,4,5,6,7,8,9};
    ListNode *head = make_list(v);
    print_list(ob.rotateRight(head, 4));
}

Input / Output

Input:  [1,2,3,4,5,6,7,8,9] 4
Output: [6, 7, 8, 9, 1, 2, 3, 4]