题目要求:
定义一个栈,要求用链表实现,使其具有如下功能:
(1) 栈包含7个元素,依次是67,3,88,6,1,7,0,采用尾插入法创建栈,该栈的名字叫s1,为该栈设置两个指针,一个bottom和一个top指针;
(2) 设计一个函数push,该函数完成向栈中插入元素的功能,利用push函数,将数字-9插入到s1,并将栈里的元素打印出来;
(3) 设计一个函数pop,该函数完成从栈中删除元素的功能,利用pop函数,删除此时栈里面的3个元素,将该栈打印出来;
(4) 设计一个函数length,求出此时栈内元素的个数。
参考代码:
#include <stdio.h>
#include <stdlib.h>
//定义结点
struct node{
int data;
struct node *next;
};
//定义双指针
struct stack{
struct node *top;
struct node *bottom;
};
//初始化
struct stack* init(){
struct stack* s1=(struct stack*)malloc(sizeof(struct stack));
s1->top=NULL;
s1->bottom=NULL;
struct node* link_node;
int arr[]={67,3,88,6,1,7,0};
int i;
for(i=0;i<7;i++){
link_node = (struct node*)malloc(sizeof(struct node));
link_node->data=arr[i];
link_node->next=NULL;
if(i==0){
s1->bottom=link_node;
}else{
s1->top->next=link_node;
}
s1->top=link_node;
}
link_node = (struct node*)malloc(sizeof(struct node));
link_node->data=NULL;
link_node->next=NULL;
s1->top->next=link_node;
s1->top=link_node;
return s1;
};
//进栈
struct stack* push(struct stack *s, int e){
s->top->data=e;
struct node* link_node = (struct node*)malloc(sizeof(struct node));
link_node->data=NULL;
link_node->next=NULL;
s->top->next=link_node;
s->top=link_node;
return s;
}
//出栈
struct stack* pop(struct stack* s_pop){
struct node *temp=s_pop->bottom;
if(s_pop->bottom==s_pop->top){
printf("此时栈已经为空!\n");
return s_pop;
}else{
for(temp;temp->next!=NULL;temp=temp->next){
if(temp->next->next==NULL){
free(temp->next);
temp->next=NULL;
temp->data=NULL;
s_pop->top=temp;
return s_pop;
}
}
}
}
//统计总数
void length(struct stack* s_length){
int i=0;
struct node *temp=s_length->bottom;
if(s_length->bottom==s_length->top){
printf("此时栈中元素个数为0\n");
}else{
for(temp;temp->next!=NULL;temp=temp->next){
i++;
}
printf("此时栈中元素个数为%d个!\n",i);
}
}
//打印
void print_stack(struct stack* s_print){
struct node *temp=s_print->bottom;
if(s_print->bottom==s_print->top){
printf("此时栈已经为空!\n");
}else{
printf("栈中的元素:");
for(temp;temp->next!=NULL;temp=temp->next){
if(temp->next->next==NULL)
printf("%d \n",temp->data);
else
printf("%d,",temp->data);
}
}
}
//main函数
int main() {
struct stack* result;
//初始化
result=init();
//打印
print_stack(result);
//进栈
result=push(result,-9);
//打印
print_stack(result);
//出栈,调用三次
result=pop(result);
result=pop(result);
result=pop(result);
//打印
print_stack(result);
//长度
length(result);
system("pause");
return 0;
}
实验结果:
1.初始化栈:
2.调用push函数,将-9插入到栈中:
3.调用3次pop函数,出栈3个元素:
4.调用length函数,扫描栈的长度: