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

Xóa node cuối (tail) danh sách liên kết đơn C++


Cho danh sách liên kết đơn, xóa node cuối cùng (tail). Nếu danh sách rỗng thì không làm gì. Ví dụ:

Đầu vào: 1→2→3→4→5 → Đầu ra: 1→2→3→4.

Phương pháp: Duyệt tìm node trước tail

  • Dùng con trỏ prev = nullptr, temp = head.
  • Duyệt cho đến khi temp->next == nullptr (temp là tail).
  • Cập nhật prev->next = nullptr, xóa temp.
  • Trường hợp đặc biệt: danh sách chỉ 1 node → xóa head, đặt head = nullptr.

Ví dụ mã nguồn

#include <iostream>
using namespace std;

class Node {
public:
    int data;
    Node* next;
    Node(int d) : data(d), next(nullptr) {}
};

void insertAtHead(Node* &head, int data) {
    Node* n = new Node(data);
    n->next = head;
    head = n;
}

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

void deleteAtTail(Node* head) {
    if (!head) return;
    if (!head->next) { delete head; head = nullptr; return; } // cần truyền head bằng tham chiếu để sửa head
    Node *prev = nullptr, *temp = head;
    while (temp->next) {
        prev = temp;
        temp = temp->next;
    }
    delete temp;
    prev->next = nullptr;
}

int main() {
    Node* head = nullptr;
    insertAtHead(head, 5);
    insertAtHead(head, 4);
    insertAtHead(head, 3);
    insertAtHead(head, 2);
    insertAtHead(head, 1);
    deleteAtTail(head);
    printList(head); // 1->2->3->4->
    return 0;
}

Kết quả

1->2->3->4->

Lưu ý: hàm deleteAtTail nên nhận Node* &head để xử lý trường hợp 1 node.