Code C++ cài đặt danh sách liên kết vòng đơn gồm các chức năng sau:
- Hàm tạo node mới
- Hàm đếm số lượng node
- Hàm thêm node vào đầu danh sách
- Hàm thêm node vào cuối danh sách
- Hàm in danh sách
Và ngay bên dưới đây là code C++ cài đặt danh sách liên kết vòng đơn với những tính năng như trên:
#include <stdio.h>
#include <stdlib.h>
//Khai báo kiểu dữ liệu Node
struct Node {
int data;
struct Node * next;
};
typedef struct Node NODE;
//Hàm tạo node mới
NODE * CreateNewNode(int data)
{
NODE * newNode = (NODE *) malloc (sizeof(NODE));
newNode -> data = data;
return newNode;
}
//Hàm in danh sách
void Display(NODE * tail)
{
NODE * current = tail;
if (tail != NULL)
{
do
{
current = current -> next;
printf(" %d -> ", current -> data);
}
while (current != tail);
}
}
//Hàm đếm số lượng node
int Length(NODE * tail)
{
NODE * current = tail;
int i = 1;
if (tail == NULL)
{
return 0;
}
else
{
current = current -> next;
while (current != tail)
{
i++;
current = current -> next;
}
}
return i;
}
//Hàm thêm vào đầu danh sách
NODE * InsertAtHead(NODE * tail, int data)
{
NODE * newNode = CreateNewNode(data);
if (tail == NULL)
{
tail = newNode;
newNode -> next = newNode;
}
else
{
newNode -> next = tail -> next;
tail -> next = newNode;
}
return tail;
}
//Hàm thêm vào cuối danh sách
NODE * InsertAtEnd(NODE * tail, int data)
{
return InsertAtHead(tail, data) -> next;
}
int main()
{
NODE * cll = NULL;
int option, data, location;
while (1)
{
printf("\n====================MENU====================");
printf("\n1. Them nut");
printf("\n2. In danh sach");
printf("\n3. Thoat\n");
printf("Menu chon: ");
scanf("%d", &option);
if (option == 1)
{
printf("Nhap du lieu de them vao danh sach: ");
scanf("%d", &data);
if(data%2==0)
{
cll = InsertAtHead(cll, data);
}
else
{
cll = InsertAtEnd(cll, data);
}
}
else if (option == 2)
{
Display(cll);
}
else if (option == 3)
{
break;
}
}
return 0;
}
Hy vọng hữu ích với bạn!
Nosomovo