數據結構之鏈棧的基本操作(出棧,入棧,顯示,求棧的長度)


 

//將12345依次入棧,取棧頂元素,將6,7入棧,求棧中元素個數,將7出棧,將6出棧,將5出棧,最后全部出棧依次輸出
#include<iostream>
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define maxsize 100
using namespace std;
typedef struct node
{
int data;
struct node *next;
}lnode ,*linkstack;

void init(linkstack *top)
{
if( ( (*top)=(linkstack)malloc(sizeof(lnode)) )==NULL )//(給*top分配一個存儲空間讓top指向這個空間)
exit(-1);
(*top)->next=NULL;

}
int empty(linkstack top)
{
if(top->next==NULL)
return 1;
else
return 0;
}
int get(linkstack top,int *e)
{
lnode *p;
p=top->next;
if(!p)
{
cout<<"棧已空!";
return 0;
}
else
{
*e=p->data;
return 1;
}
}


int push(linkstack top,int e)
{
lnode *p;
if( (p=(linkstack)malloc(sizeof(lnode)))==NULL )//(給*top分配一個存儲空間讓top指向這個空間)
{
printf("分配內存失敗");
exit(-1);
return 0;
}

p->data=e;
p->next=top->next;
top->next=p;
return 1;

}
int pop(linkstack top,int *e)
{
linkstack p=top->next;
if(p==NULL)
{
cout<<"棧已空!";
return 0;
}

top->next=p->next;
*e=p->data;
free(p);
return 1;
}


int length(linkstack top)
{
int i=0;
lnode *p=top;
while(p->next!=NULL)
{
p=p->next;
i++;
}
return i;
}

void clear(linkstack top)
{
lnode *p,*q;
p=top;
while(!p)
{
q=p;
p=p->next;
free(q);
}
}

int main()
{
linkstack s;
lnode *p;
int i;
int a[]={1,2,3,4,5};
int e;
init(&s);
cout<<"將12345依次入棧!"<<endl;
for(i=0;i<sizeof(a)/sizeof(a[0]);i++)
{
push(s,a[i]);
}

cout<<"棧頂元素為:";
if(get(s,&e)==0)
{
cout<<"棧為空";
return 0;
}
else
{
cout<<e;
cout<<endl;
}
cout<<"將6入棧"<<endl;
push(s,6);
cout<<"將7入棧"<<endl;
push(s,7);
cout<<"棧中元素個數為:"<<length(s);
cout<<endl;

cout<<"將7出棧"<<" ";
pop(s,&e);
cout<<"將6出棧"<<" ";
pop(s,&e);
cout<<"將5出棧"<<endl;
pop(s,&e);

cout<<"棧中元素個數為:"<<length(s);
cout<<endl;

cout<<"出棧元素的序列:";
while(!empty(s))
{
pop(s,&e);
cout<<e;
}
cout<<endl;

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM