前面已经介绍了链表:
数据结构01----C语言单向链表
数据结构02----C原因双向链表
今天我们来看下数据结构中的栈的介绍和C语言的实现。
四、栈
1.简介
栈是限定只在表头进行插入(入栈或者压栈)与删除(出栈或者弹栈)操作的线性表,这里的表头称为栈顶,表尾称为栈底。其中,出栈的第一个元素称为栈顶元素,出栈的最后一个元素称为栈底元素。由此可见,栈 是一种 后进先出 的数据存储结构。如下图:
其中1/2/3/4表示入栈的顺序。
1.链栈
栈的C语言实现,我们这里分两种介绍,一种是链栈,一种是顺序栈。
先来看链栈,如下图:
看着图,链栈是不是看上去有点像一个特殊的单链表,只不过这个单链表的插入和删除只能在头部进行。
有了前面链表的基础,代码很好理解,如下:
#include <stdio.h>
#include <stdlib.h>
//1、定义结点
typedef struct Link
{
int data;
struct Link *next;
}link;
//3、入栈
link *push(link *head,int elem)
{
link *node=(link *)malloc(sizeof(link));
node->data=elem;
node->next=head;
head=node;
return head;
}
//4、出栈
link *pop(link *head)
{
if (head==NULL)
{
printf("栈空!\n");
}
else
{
link *temp=head;
printf("%d\n",head->data);
head=head->next;
free(temp);
}
return head;
}
int main(int argc, char const *argv[])
{
//2、初始化
link *head=NULL;
head=push(head,10);
head=push(head,20);
head=push(head,30);
head=push(head,40);
head=pop(head);
head=pop(head);
head=pop(head);
head=pop(head);
head=pop(head);
return 0;
}
运行结果:
最基本的操作也就那几个步骤:
①定义节点
②初始化
②进行插入删除操作(在首元节点这里操作)
2.顺序栈
循序栈的实现:
用数组下标表示指向栈顶的指针top,每入栈一个元素top+1;每出栈一个元素,栈顶指针top-1
#include <stdio.h>
//入栈
void push(int *a,int *top,int elem)
{
a[++(*top)]=elem;
}
//出栈
void pop(int *a,int *top)
{
if (*top==-1)
{
printf("栈空\n");
}
else
{
printf("%d\n",a[(*top)--]);
}
}
//主函数
int main(int argc, char const *argv[])
{
int a[10];
int top=-1;
//入栈
push(a,&top,10);
push(a,&top,20);
push(a,&top,30);
push(a,&top,40);
//出栈
pop(a,&top);
pop(a,&top);
pop(a,&top);
pop(a,&top);
pop(a,&top);
return 0;
}
运行结果:
继续学习,请往后看:
数据结构04----队列