1. 程式人生 > >C++ 連結串列棧及常用函式實現

C++ 連結串列棧及常用函式實現


#include<iostream>
using namespace std;
typedef struct Node
{
	int data;
	struct Node* next;
}Node;
typedef struct Stack
{
	Node* top;
	Node* head;
}Stack;
void init(Stack &S);
void push(Stack &S, int i);
void pop(Stack &S, int &i);
void Print(Stack S);


int main()
{
	Stack S;
	S.head = new Node;
	init(S);
	int i,f;
	cout << "請輸入1.push 2.pop 3.print 0.break"<< endl;
	cin >> f;
	while (f)
	{

		switch (f)
		{
		case 1:
			cout << "請輸入push的數字:" << endl;
			cin >> i;
			push(S, i);
			Print(S);
			break;
		case 2:
			pop(S, i);
			Print(S);
			break;
		case 3:
			Print(S);
			break;

		default:
			break;
		}
		cout << "請輸入1.push 2.pop 3.print 0.break" << endl;
		cin >> f;
	}
	getchar();
	getchar();
	return 0;
}
void init(Stack &S)
{
	S.top = S.head;
	(*S.head).data = 0;
	(*S.head).next = NULL;
}
void push(Stack &S, int i)
{
	Node* p = S.head;
	S.top = new Node;
	while((*p).next != NULL)
	{
		p = p->next;
	}
	S.top ->data= i;
	(*p).next = S.top;
	S.top->next = NULL;
}
void pop(Stack &S, int &i)
{
	if (S.head->next==NULL)
	{
		cout << "棧空,操作失敗" << endl;
	}
	else if (S.head->next==S.top)
	{
		i = S.top->data;
		free (S.top);
		S.top ==S.head;
		S.head->next = NULL;
		cout << "棧已空" << endl;
		cout << "彈出元素" << i<<endl;
	}
	else
	{
		Node *p = S.head;
		while (p->next!= S.top)
			p = p->next;
		i = S.top->data;
		free(S.top);
		S.top = p;
		p->next = NULL;
		cout << "彈出元素" << i<<endl;
	}
}
void Print(Stack S)
{
	Node* p = S.head;
	int e;
	if (p->next == NULL)
		cout << "棧為空" << endl;
	else
	{

		cout << "輸出棧:" << endl;
		while (p->next != NULL)
		{
			p = p->next;
			e = p->data;
			cout << e << endl;
		}
	}
}