使用链表实现栈操作

编程入门 行业动态 更新时间:2024-10-24 22:17:28

使用<a href=https://www.elefans.com/category/jswz/34/1769662.html style=链表实现栈操作"/>

使用链表实现栈操作

源码如下:

#include <stdio.h>
#include <stdlib.h>
struct node
{int info;struct node *link;
};
struct node *top = NULL, *temp;
void push(struct node *);
void pop(struct node *);
void display(struct node *);int main()
{int x = 0, item;printf("\t****stack using linked list****\n");while (x != 4){printf("\n1. Push\n2. Pop\n3. Display\n4. Exit\n");printf("Enter your choice: ");scanf("%d", &x);switch (x){case 1:push(top);break;case 2:pop(top);break;case 3:display(top);break;case 4:return 0;}}
}void push(struct node *p)
{int item;struct node *temp;temp = (struct node *)malloc(sizeof(struct node));printf("\nEnter element to be inserted: ");scanf("%d", &item);temp->info = item;temp->link = top;top = temp;printf("Inserted succesfully.\n");
}void pop(struct node *p)
{int item;struct node *temp;if (top == NULL)printf("\nStack is empty.\n");else{item = top->info;temp = top;top = top->link;free(temp);printf("\nElement popped is %d.\n", item);}
}void display(struct node *p)
{if (top == NULL)printf("\nStack is empty.\n");else{printf("\nElements in the stack are:\n");while (p != NULL){printf("\t%d\n", p->info);p = p->link;}// printf("%d\n",p->info);}
}

测试运行:

    ****stack using linked list****

1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1

Enter element to be inserted: 88 //入栈
Inserted succesfully.

1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 3

Elements in the stack are:
    88

1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1

Enter element to be inserted: 22 //入栈
Inserted succesfully.

1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 3

Elements in the stack are:
    22
    88

1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 2

Element popped is 22. //出栈

1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 3

Elements in the stack are:
    88
 

更多推荐

使用链表实现栈操作

本文发布于:2023-12-03 20:48:43,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1657496.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:链表   操作

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!