链栈的基本操作实现

1. 链栈含头结点模型示意图如下:

2. 链栈结构定义如下:

struct StackNode {
	int data;
	StackNode* next;
};

3. 链栈的基本操作函数如下:

  • StackNode* createStack(); // 创建栈头结点
  • void Push(StackNode* head, int item); // 入栈
  • int Pop(StackNode* head); // 出栈,并返回出栈数据
  • int getStackLength(StackNode* head); // 获取栈元素个数

4. 具体代码实现如下:

#include <iostream>

using namespace std;

// 结点结构
struct StackNode {
	int data;
	StackNode* next;
};

// 创建栈头结点
StackNode* createStack() {
	StackNode* head = (StackNode*)malloc(sizeof(StackNode));
	if (head == NULL) {
		cout << "Memory allocate failed." << endl;
		return NULL;
	}
	head->data = 0;
	head->next = NULL;
	return head;
}

// 入栈
void Push(StackNode* head, int item) {
	if (head == NULL) {
		return;
	}
	StackNode* node = (StackNode*)malloc(sizeof(StackNode));
	if (node == NULL) {
		cout << "Memory allocate failed." << endl;
		return;
	}
	node->data = item;
	node->next = head->next;
	head->next = node;
}

// 出栈
int Pop(StackNode* head) {
	if (head == NULL || head->next == NULL) {
		cout << "Error." << endl;
		return 0;
	}
	StackNode* node = (StackNode*)malloc(sizeof(StackNode));
	if (node == NULL) {
		cout << "Memory allocate failed." << endl;
		return 0;
	}
	StackNode* temp = head->next;
	head->next = temp->next;
	int val = temp->data;
	free(temp);
	return val;
}

// 获取栈元素个数
int getStackLength(StackNode* head) {
	if (head == NULL || head->next == NULL) {
		return 0;
	}
	StackNode* p = head->next;
	int len = 0;
	while (p != NULL) {
		len++;
		p = p->next;
	}
	return len;
}

int main() {
	StackNode* head = NULL;
	head = createStack();
	Push(head, 5);
	Push(head, 4);
	Push(head, 3);
	cout << getStackLength(head) << endl;
	cout << Pop(head) << endl;
	cout << Pop(head) << endl;
	cout << getStackLength(head) << endl;
	cout << Pop(head) << endl;
	cout << getStackLength(head) << endl;
	system("pause");
	return 0;
}

5. 运行结果截图如下:

posted @ 2018-07-05 15:09  一路一沙  阅读(2671)  评论(0编辑  收藏  举报