数据结构学习

线性结构

学习内容包括堆栈的顺序存储和链式存储

顺序存储

用列表实现,创建一个结构体。Last表示当前位置。

#include <iostream>
using namespace std;

typedef int Position;
struct LNode
{
	int Data[10];
	Position Last;
};

void Creat(LNode *L)				//初始化
{
	L->Last = -1;
}

bool IsEmpty(LNode *L)
{
	if (L->Last == -1)
		return true;
	else
		return false;
}

bool IsFull(LNode *L)
{
	if (L->Last == 9)
		return true;
	else
		return false;
}

bool Push(LNode *L, int num)
{
	if (IsFull(L)) {
		cout << "Full!" << endl;
		return false;
	}
	else
	{
		L->Last++;
		int p = L->Last;
		L->Data[p] = num;
		return true;
	}
}

int Pop(LNode *L)
{
	if (IsEmpty(L))
	{
		cout << "None!" << endl;
	}
	else
	{
		return (L->Data[(L->Last)--]);
	}
}

int main()
{
	LNode *L;
	L = new LNode;
	Creat(L);

	for (int i = 0; i < 5; i++)
	{
		int num;
		cout << "Enter Number:";
		cin >> num;
		Push(L, num);
	}

	for (int i = 0; i < 5; i++)
	{
		int num;
		num = Pop(L);
		cout << "Number:" << num << endl;
	}
	return 0;
}

链式存储

用链表实现。链表使用需要注意添加和删除节点的步骤顺序。

#include <iostream>
using namespace std;

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


void CreatStack(ListNode *s)				//初始化
{
	s->next = NULL;
}

bool IsEmpty(ListNode *s)					//判断是否为空,空为true
{
	if (s->next != NULL)
		return false;
	else
		return true;
}

void Push(ListNode *s, int x)				//插入元素
{
	ListNode *p;
	p = new ListNode;
	p->data = x;
	p->next = s->next;
	s->next = p;
}

int Pop(ListNode *s, int &e)				//出栈
{
	ListNode *p;
	if (IsEmpty(s))
		return 0;
	else
	{
		p = s->next;
		e = p->data;
		s->next = p->next;
		delete p;
	}
}

void Destroy(ListNode *s)
{
	ListNode *p;
	while (!IsEmpty(s))
	{
		p = s->next;
		s->next = p->next;
		delete p;
	}
}

int main()
{
	ListNode *s;
	s = new ListNode;
	CreatStack(s);
	int num;
	if (IsEmpty(s))
		cout << "Empty!" << endl;
	else
		cout << "Not Empty!";
	for (int i = 0; i < 7; i++)
	{
		cout << "Enter number:";
		cin >> num;
		Push(s, num);
	}
	for (int i = 0; i < 3; i++)
	{
		Pop(s, num);
		cout << "data:" << num << endl;
	}

	if (IsEmpty(s))
		cout << "Empty!";
	else
		cout << "Not Empty!";

	Destroy(s);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值