c++ 关于链表和链表实现栈

本文介绍了一种使用链表实现栈的数据结构方法,并提供了一个简单的C++实现案例。通过定义链表节点结构,创建链表初始化函数,实现了栈的基本操作如push、pop及获取栈大小等功能。此外还展示了如何利用该栈结构进行数据的压入和弹出操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <vector>

using namespace std;

struct Node{
	int num;
	Node * next;
	
	Node(int a){
		this->num = a;
		this->next = NULL;
	}
};
//用数组初始化链表 
Node * init(int * nums, int size)
{
	Node * root = new Node(0);
	//1.头结点很方便。 2.root必须有指向一个对象,如果是NULL,则没没办法赋值 
	Node * pre = root;
	for(int i = 0; i < size; i++){
		Node * temp = new Node(nums[i]);
		pre->next = temp;
		pre = pre->next;
	}
	return root;
}

void print(Node * root)
{
	Node * iterator = root;
	while(iterator != NULL){
		cout << iterator->num << " ";
		iterator = iterator->next; 
	}
}

class MyStack{
	
private:
	Node * head;
	
public:
	MyStack(){
		head = NULL;
	}
	
	void push(int n)
	{
		Node * temp = new Node(n);
		if(head != NULL){
			temp->next = head;//栈顶在链表的头部 
		}
		head = temp;
	}
	
	void pop()
	{
		if(head == NULL)return ;
		head = head->next;
	}
	
	int size()
	{
		int count = 0;
		Node * p = head;
		while(p != NULL){
			count++;
			p = p->next;
		}
		return count;
	}
	
	void print()
	{
		Node * p = head;
		while(p != NULL){
			cout << p->num << " ";
			p = p->next;
		}
		cout << endl;
	}
};

int main()
{
	int nums[5] = {1, 2, 3, 4, 5};
	
	MyStack s;
	
	for(int i = 0; i < 5; i++){
		s.push(nums[i]);
	}
	//s.push(1);
	s.print();
	cout << s.size() << endl;
	s.pop();
	s.print();
	cout << s.size() << endl;

	return 0;
}

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值