數據結構 鏈棧初始化及入出棧

#include<iostream>
#include<stdlib.h>
using namespace std;

typedef struct chain_stack{
	int data;
	chain_stack *next;
}chain_stack;

int push(chain_stack *S,int x){//頭插法
	// chain_stack *head2;
	chain_stack *node=(chain_stack *)malloc(sizeof(chain_stack));//創建一個節點,因爲是malloc函數分配,分配的空間並不會因爲函數運行結束而結束
	node->data=x;//給節點賦值
	chain_stack *temp=S->next;
	node->next=temp;
	S->next=node;
	// node->next=temp;

	return 1;
}
void print(chain_stack *S){
	chain_stack *head=S->next;
	while(head!=NULL){
		cout<<head->data<<" ";
		head=head->next;
	}
	cout<<endl;
}
int pop(chain_stack *S){
	chain_stack *head=S->next;
	if(head!=NULL){
		chain_stack *temp=head;
		int x=head->data;
		S->next=head->next;
		free(temp);
		return x;
	}
	return -99999;
}
int main(){
	// cout<<"asdasd"<<endl;
	chain_stack *S=(chain_stack *)malloc(sizeof(chain_stack));
	S->next=NULL;
	// cout<<"asd"<<endl;
	cout<<"push "<<push(S,2)<<endl;
	cout<<"push "<<push(S,3)<<endl;
	print(S);
	cout<<"pop "<<pop(S)<<endl;
	print(S);

	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章