Professional Documents
Culture Documents
struct Node
{
Data info;
Node* next;
};
struct Node
{
int value;
Node* next;
};
struct Node
{
int data;
Node* next;
struct List
{
Node* head;
Node* tail;
List() {
head = nullptr;
tail = nullptr;
}
};
Nếu biết được địa chỉ đầu tiên trong danh sách
liên kết ta có thể dựa vào thông tin next để
truy xuất đến các phần tử còn lại, do đó ta sẽ
dùng một con trỏ head để lưu lại địa chỉ Node
đầu tiên của danh sách.
https://www.stdio.vn/giai-thuat-lap-trinh/danh-sach-lien-ket-don-elmLe 2/9
14/3/2021 Danh Sách Liên Kết Đơn — Giải Thuật Lập Trình
insertToHead(Node* node)
{
node->next = head;
head = node;
}
https://www.stdio.vn/giai-thuat-lap-trinh/danh-sach-lien-ket-don-elmLe 3/9
14/3/2021 Danh Sách Liên Kết Đơn — Giải Thuật Lập Trình
insertToTail(Node* node)
{
if (tail != nullptr)
tail->next = node;
else
{
head = node;
tail = node;
}
}
https://www.stdio.vn/giai-thuat-lap-trinh/danh-sach-lien-ket-don-elmLe 5/9
14/3/2021 Danh Sách Liên Kết Đơn — Giải Thuật Lập Trình
removeAtHead()
{
if (head == nullptr)
return;
Node* temp = head;
head = head->next;
delete temp;
}
https://www.stdio.vn/giai-thuat-lap-trinh/danh-sach-lien-ket-don-elmLe 6/9
14/3/2021 Danh Sách Liên Kết Đơn — Giải Thuật Lập Trình
removeAfter(Node* q)
{
Node* temp = q->next;
q->next = temp->next;
delete temp;
}
Node* p;
p = list.head;
while (p != NULL)
{
// Process Node
p = p->next;
}
Lời kết
Source code được viết theo hướng cấu trúc để
các bạn chưa có khái niệm về hướng đối tượng
có thể tiếp cận một cách dễ dàng. Có thể thấy
được, danh sách liên kết đã khắc phục được
nhược điểm của mảng - đó là kích thước cố định.
#include
using namespace std;
struct Node
{
int data;
https://www.stdio.vn/giai-thuat-lap-trinh/danh-sach-lien-ket-don-elmLe 7/9
14/3/2021 Danh Sách Liên Kết Đơn — Giải Thuật Lập Trình
Node* next;
struct List
{
Node* head;
Node* tail;
List() {
head = nullptr;
tail = nullptr;
}
insertToHead(Node* node)
{
node->next = head;
head = node;
}
insertToTail(Node* node)
{
if (tail != nullptr)
tail->next = node;
else
{
head = node;
tail = node;
}
}
removeAtHead()
{
if (head == nullptr)
return;
Node* temp = head;
head = head->next;
delete temp;
}
removeAfter(Node* q)
{
Node* temp = q->next;
https://www.stdio.vn/giai-thuat-lap-trinh/danh-sach-lien-ket-don-elmLe 8/9
14/3/2021 Danh Sách Liên Kết Đơn — Giải Thuật Lập Trình
q->next = temp->next;
delete temp;
}
iterate()
{
Node* p;
p = head;
while (p != NULL)
{
// TODO:
cout << p->value << endl;
p = p->next;
}
}
while (p != NULL)
{
if (p->value == _value)
return p;
p = p->next;
}
return nullptr;
}
};
// Test
int main()
{
List li;
li.insertToHead(3);
li.insertToHead(2);
li.insertToTail(4);
Node* q = li.find(3);
li.insertAfter(new Node(9), q);
return 0;
}
https://www.stdio.vn/giai-thuat-lap-trinh/danh-sach-lien-ket-don-elmLe 9/9