Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Di chuyển nút đầu về cuối danh sách liên kết C++

Cho danh sách liên kết đơn, di chuyển nút đầu tiên (head) xuống cuối danh sách.

Ví dụ

Input: 1→2→3→4→5→NULL
Output: 2→3→4→5→1→NULL

Thuật toán

  • Nếu rỗng hoặc 1 nút → trả về.
  • Lưu first = head.
  • Tìm nút cuối last.
  • head = first->next.
  • first->next = NULL.
  • last->next = first.

Triển khai C++

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

struct Node { int data; Node* next; };

void moveFirstToEnd(Node** head) {
    if (!*head || !(*head)->next) return;
    Node* first = *head;
    Node* last = *head;
    while (last->next) last = last->next;

    *head = first->next;
    first->next = nullptr;
    last->next = first;
}

void push(Node** head, int data) {
    Node* n = new Node{data, *head};
    *head = n;
}

void printList(Node* head) {
    while (head) { cout << head->data << "->"; head = head->next; }
    cout << "NULL" << endl;
}

int main() {
    Node* head = nullptr;
    for (int i = 9; i >= 1; i--) push(&head, i);
    moveFirstToEnd(&head);
    printList(head); // 2->3->...->9->1->NULL
    return 0;
}

Kết quả

2->3->4->5->6->7->8->9->1->NULL