使用 C 语言中的链表来解释堆栈
通过动态分配内存,可以避免堆栈上溢和堆栈下溢。
在 C 编程语言中堆栈下执行的操作如下 −
- 压入
- 弹出
压入
以下是链表的一个基本实现 −
&item = 10 newnode = (node*) malloc (sizeof (node)); newnode ->data = item; newnode ->link = NULL; newnode ->link = start; start = newnode;

弹出
语法如下 −
语法
if (start = = NULL)
printf("Deletion is not possible.List is empty")
else{
temp = start;
start = start link;
free (temp);
}程序
以下是使用链表实现堆栈的 C 程序 −
#include <stdio.h>
#include <stdlib.h>
struct node{
int info;
struct node *ptr;
}*top,*top1,*temp;
int topelement();
void push(int data);
void pop();
void empty();
void display();
void destroy();
void stack_count();
void create();
int count = 0;
void main(){
int no, ch, e;
printf("
1 - Push");
printf("
2 - Pop");
printf("
3 - Top");
printf("
4 - Empty");
printf("
5 - Exit");
printf("
6 - Display");
printf("
7 - Stack Count");
printf("
8 - Destroy stack");
create();
while (1){
printf("
Enter choice : ");
scanf("%d", &ch);
switch (ch){
case 1:
printf("Enter element : ");
scanf("%d", &no);
push(no);
break;
case 2:
pop();
break;
case 3:
if (top == NULL)
printf("stack is empty");
else{
e = topelement();
printf("
Top element : %d", e);
}
break;
case 4:
empty();
break;
case 5:
exit(0);
case 6:
display();
break;
case 7:
stack_count();
break;
case 8:
destroy();
break;
default :
printf(" wrong choice:Try again ");
break;
}
}
}
//empty stack
void create(){
top = NULL;
}
void stack_count(){
printf("
no: of elements in stack : %d", count);
}
//push data
void push(int data){
if (top == NULL){
top =(struct node *)malloc(1*sizeof(struct node));
top->ptr = NULL;
top->info = data;
}
else{
temp =(struct node *)malloc(1*sizeof(struct node));
temp->ptr = top;
temp->info = data;
top = temp;
}
count++;
}
void display(){
top1 = top;
if (top1 == NULL){
printf("empty stack");
return;
}
while (top1 != NULL){
printf("%d ", top1->info);
top1 = top1->ptr;
}
}
void pop(){
top1 = top;
if (top1 == NULL){
printf("
error");
return;
}
else
top1 = top1->ptr;
printf("
Popped value : %d", top->info);
free(top);
top = top1;
count--;
}
int topelement(){
return(top->info);
}
//check stack empty or not
void empty(){
if (top == NULL)
printf("
empty stack");
else
printf("
stack not empty with %d values", count);
}
void destroy(){
top1 = top;
while (top1 != NULL){
top1 = top->ptr;
free(top);
top = top1;
top1 = top1->ptr;
}
free(top1);
top = NULL;
printf("
all are destroyed");
count = 0;
}输出
当上述程序执行时,它会生成以下结果 −
1 - Push 2 - Pop 3 - Top 4 - Empty 5 - Exit 6 - Display 7 - Stack Count 8 - Destroy stack Enter choice: 1 Enter element: 23 Enter choice: 1 Enter element: 45 Enter choice: 1 Enter element: 56 Enter choice: 2 Popped value: 56 Enter choice: 6 45 23 Enter choice: 8 all are destroyed Enter choice: 6 empty stack Enter choice: 5
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP