C++:用类实现链表,队列,栈

用类实现链表:

#include<iostream>
using namespace std;

class List
{
	struct Node
	{
		int Nval;
		Node* pNext;
	};
private:
	Node* pHead = NULL;
	Node* pEnd = NULL;
public:
	void AddNode(int n);
	void DelNode(int n);
	void walk();
};
void List::AddNode(int k)
{
	Node* ptemp = new Node;
	ptemp->Nval = k;
	ptemp->pNext = NULL;
	if (NULL == pHead)
	{
		pHead = ptemp;
	}
	else
	{
		pEnd->pNext = ptemp;
	}
	pEnd = ptemp;
}
void List::DelNode(int n)
{
	Node* pdel = NULL;
	if (pHead->Nval == n)
	{
		pdel = pHead;
		pHead = pHead->pNext;
		free(pdel);
		pdel = NULL;
		return;
	}
	Node* pmark = pHead;
	while (pmark->pNext != NULL)
	{
		if (pmark->pNext->Nval == n)
		{
			pdel = pmark->pNext;
			pmark->pNext = pmark->pNext->pNext;
			free(pdel);
			pdel = NULL;
			if (pmark->pNext == NULL)
			{
				pEnd = pmark;
			}
			return;
		}
		pmark = pmark->pNext;
	}
}
void List::walk()
{
	while (pHead != NULL)
	{
		cout << pHead->Nval << endl;
		pHead = pHead->pNext;
	}
}

int main()
{
	List list;
	list.AddNode(1);
	list.AddNode(2);
	list.AddNode(3);

	list.DelNode(1);
	list.DelNode(2);
	list.walk();


	return 0;
}

用类实现队列:

#include<iostream>
using namespace std;

class Queue
{
	struct Node
	{
		int Nval;
		Node* pNext;
	};
private:
	Node* pHead = NULL;
	Node* pEnd = NULL;
public:
	void Push(int n);
	int pop();

};
void Queue::Push(int n)
{
	Node* pTemp = new Node;
	pTemp->Nval = n;
	pTemp->pNext = NULL;

	if (pHead == NULL)
	{
		pHead = pTemp;
	}
	else
	{
		pEnd->pNext = pTemp;
	}
	pEnd = pTemp;
}
int Queue::pop()
{
	if (pHead != NULL)
	{
		Node* pdel = pHead;
		pHead = pHead->pNext;
		int n = pdel->Nval;
		free(pdel);
		pdel = NULL;
		if (NULL == pHead)
		{
			pEnd = NULL;
		}
		return n;
	}
	return -1;
}


int main()
{
	Queue yan;
	yan.Push(1);
	yan.Push(2);
	yan.Push(3);

	cout << yan.pop() << endl;
	cout << yan.pop() << endl;
	cout << yan.pop() << endl;


	return 0;
}

用类实现栈:

#include<iostream>
using namespace std;

class List
{
	struct Node
	{
		int n;
		Node* pnext;
	};
private:
	Node* ptop = NULL;
public:
	void push(int n);
	int pop();
};
void List::push(int n)
{
	Node* ptemp = new Node;
	ptemp->n = n;
	ptemp->pnext = NULL;
	if (ptop != NULL)
	{
		ptemp->pnext = ptop;
		ptop = ptemp;
	}
	else
	{
		ptop = ptemp;
	}
}
int List::pop()
{
	if (ptop != NULL)
	{
		Node* pdel = ptop;
		ptop = ptop->pnext;
		int k = pdel->n;
		free(pdel);
		pdel = NULL;
		
		return k;
	}
	return -1;
}

int main()
{
	List k;
	k.push(1);
	k.push(2);
	k.push(3);

	cout << k.pop()<< endl;
	cout << k.pop() << endl;
	cout << k.pop() << endl;

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值