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

Xóa node đầu (head) danh sách liên kết đơn C++


Cho danh sách liên kết đơn, xóa node đầu tiên (head). Ví dụ:

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

Phương pháp

  • Nếu head là NULL → trả về.
  • Lưu head vào temp.
  • Cập nhật head = head->next.
  • Xóa temp.

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 deleteAtHead(Node* &head) {
    if (!head) return;
    Node* temp = head;
    head = head->next;
    delete temp;
}

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

Kết quả

3->2->1->

Thao tác O(1).