链表栈与队列 C语言实现
!!!本代码学习参考部分较多,仅供提交作业及课内交流使用,并无任何借鉴价值。
链表栈
//Author DICTATOR
//This is Stack Code
#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
int data;
struct Node* next;
}node;
typedef struct Stack{ //此代码采用栈顶栈尾双指针
node* top;
node* buttom;
}stack;
stack* CreatEmptyStack(){ //初始化
node* NewNode = (node*)malloc(sizeof(node));
NewNode->next = NULL;
stack* st = (stack*)malloc(sizeof(stack));
st->top = st->buttom = NewNode;
return st;
}
void Push(stack* st,int data){ //元素入栈
node* NewNode = (node*)malloc(sizeof(node));
NewNode->data = data;
NewNode->next = st->top;
st->top = NewNode;
}
int IsEmpty(stack* st){ //判断栈是否为空
return st->top == st->buttom; //若栈顶指针与栈尾指针相同,则栈为空
}
void Pop(stack* st){ //元素出栈
if (IsEmpty(st)){ //判断是否为空
return;
}
node* temp = st->top;
printf("%d\n",temp->data); //为了有出栈的直观反映,在此函数中printf
st->top = temp->next;
free(temp); //释放内存
}
void Clear(stack* st){ //清空栈
if (IsEmpty(st)){
return;
}
node* temp1 = st->top;
node* temp2 = NULL;
while (temp1 != st->buttom){ //temp1与栈尾指针相同时,栈完成清空
temp2 = temp1->next;
free(temp1);
temp1 = temp2;
free(temp2);
}
st->top = st->buttom; //将栈顶赋为栈尾
printf("栈清空完成!\n");
}
void Destory(stack* st){ //销毁栈
Clear(st); //首先完成清空
free(st); //释放栈内存
st = NULL;
printf("栈已销毁!\n");
}
int main(){
int k;
int n = 5; //为了方便书写,随意取了5作为入栈元素数量
stack* st;
st = CreatEmptyStack();
printf("开始进栈:\n");
while (n--){
scanf("%d",&k);
Push(st,k);
}
Pop(st);
Pop(st);
Clear(st);
Destory(st);
return 0;
}
将链表熟悉后,栈的代码书写并没有那么困难。但目前个人觉得链表栈的运用范围比较小,后进先出的限制局限了栈的使用。 并且个人并没有体会到链表栈优于数组栈的方面。
链表队列
//Author DICTATOR
//This is queue code
#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
int data;
struct Node* next;
}node;
typedef struct Queue{
node* head;
node* tail;
}queue;
queue* CreatEmptyQueue(){ //初始化
queue* qu = (queue*)malloc(sizeof(queue));
qu->head = qu->tail;
return qu;
}
node* ListHeadDelelte(node* head){ //定义头删,用于出队
if(head){
node* temp = head->next;
free(head);
return temp;
}
return head;
}
int IsEmpty(queue* qu){
return qu->head == qu->tail;
}
void Push(queue* qu,int data){ //入队
node* NewNode = (node*)malloc(sizeof(node));
NewNode->data = data;
if(!qu->head){
qu->head = qu->tail = NewNode;
return;
}
NewNode->next = qu->tail->next; //新节点进行尾插
qu->tail->next = NewNode;
qu->tail = NewNode;
return;
}
void Pop(queue* qu){ //出队
printf("%d\n",qu->head->data);
qu->head = ListHeadDelelte((node*)qu->head);
return;
}
void Clear(queue* qu){ //类似于栈的清空
if (IsEmpty(qu)){
return;
}
node* temp1 = qu->head;
node* temp2 = NULL;
while (temp1 != qu->tail){
temp2 = temp1->next;
free(temp1);
temp1 = temp2;
free(temp2);
}
qu->head = qu->tail;
printf("队列清空完成!\n");
}
void Destory(queue* qu){
Clear(qu);
free(qu);
qu = NULL;
printf("队列已销毁!\n");
}
int main(){
queue* qu = CreatEmptyQueue();
Push(qu,3); //为了方便书写检验,这里简单取三个入队
Push(qu,4);
Push(qu,5);
Pop(qu);
Destory(qu);
return 0;
}
队列与栈的区别个人感觉不大,但是队列的书写会稍微麻烦一点。总之熟练掌握链表可以较快掌握。