1.思路
定义结构体node表示链表里的节点,结构体linklist表示链表,选用两个首尾指针进行基本操作。
2.代码
#include<iostream>
using namespace std;
struct node {
int value;
node *next;
};
struct linklist { //带头尾指针的链表
node* head;
node* tail;
};
void Create(linklist* list) {
if (list == NULL) {
cout << "queue failed" << endl;
return;
}
node* tmp = (node*)malloc(sizeof(node));
tmp->next = NULL;
tmp->value = 0;
list->head = tmp;
list->tail = tmp;
return;
}
void EnQueue(linklist* list, int n) {
node* tmp = (node*)malloc(sizeof(node));
tmp->value = n;
tmp->next = NULL;
list->tail->next = tmp;
list->tail = tmp;
}
int DeQueue(linklist* list) {
if (list == NULL) {
cout << "queue failed " << endl;
return 0;
}
if(list->head == list->tail) {
cout << "list empty!" << endl;
return 0;
}
node* tmp = list->head->next;
list->head->next = tmp->next;
//若队内只要一个元素,则出队后要修改队尾指针
if(tmp == list->tail) {
list->tail = list->head;
}
int res = tmp->value;
free(tmp);
tmp = NULL;
return res;
}
bool IsEmpty(linklist* list) {
if (list == NULL) {
cout << "queue failed" << endl;
return false;
}
return list->head == list->tail;
}
void DestroyQueue(linklist* list) {
while(list->head != NULL) {
list->tail = list->head->next;
free(list->head);
list->head = list->tail;
}
}
int main() {
linklist *list = (linklist*)malloc(sizeof(linklist));
Create(list);
EnQueue(list, 1);
EnQueue(list, 5);
EnQueue(list, 3);
cout << DeQueue(list) << endl;
cout << DeQueue(list) << endl;
EnQueue(list, 9);
cout << DeQueue(list) << endl;
cout <<"is empty?" << IsEmpty(list) << endl;
cout << DeQueue(list) << endl;
cout <<"is empty?" << IsEmpty(list) << endl;
DestroyQueue(list);
free(list);
list = NULL;
cout << DeQueue(list) << endl;
return 0;
}
3.运行结果