啊哈算法——第二章:栈队列与链表

第二章:栈队列与链表

队列

显然对于队列我们只需要记住它最重要的性质:先进先出(FIFO) 即可。
队列还包括双向队列(deque,用于实现滑动窗口算法),优先队列(priority_queue,用于实现堆)等,在后面的算法内容中会详述。
调用C++STL建立队列:queue q;即建立了一个type类型的队列,名字为q。

对于队列我们只需要记住它最重要的性质:先进后出(FILO) <或后进先出> 即可。
调用C++STL建立队列:stack s;即建立了一个type类型的队列,名字为s。

链表

链表的有关内容不再赘述,此处给出使用C++实现的双向循环链表代码,包括了链表的建立,遍历,插入以及删除结点操作。

#include 
using namespace std;
int n;
struct node{
	int data;
	node* next;
	node* prior;
}*head;
//带头结点的双向循环链表。 
void SetNode(){
	head = new node;
	head->data = 0;
	head->next = head->prior = nullptr;
	
	node *p,*q;
	for(int i=1;i<=n;i++){
		int data_in;
		cin>>data_in;
		p = new node;
		p->data = data_in;
		p->next = p->prior = nullptr;
		
		if(head->next == nullptr){
			head->next = p;
			p->prior = head;
		}
		else{
			q->next = p;
			p->prior = q;
		}
		
		q = p;
	}
	
	q->next = head;
	head->prior = q;//循环 
}
bool InsertNode(int m,int v){
	//在第m个结点后面插入结点,数据为v 
	if(m > n)	return false;
	node *p = head->next;
	int cnt = 0;
	while(++cnt < m){
		p = p->next;
	}
	node *q = new node;
	q->data = v;
	q->next = p->next;
	p->next->prior = q;
	p->next = q;
	q->prior = p;
	return true;
} 
bool DeleteNode(int m){
	if(m > n)	return false;
	int cnt = 0;
	node *p = head->next;
	while(++cnt < m){
		p = p->next;
	}
	node *q = p;
	p->prior->next = p->next;
	p->next->prior = p->prior;
	delete q;
	return true;
}
void TraverseNode(){
	node *p = head->next;
	while(p != head){
		cout<<p->data<<' ';
		p = p->next;
	}
	cout<<endl;
}
int main()
{
	cin>>n;
	SetNode();
	TraverseNode();
	DeleteNode(1);
	TraverseNode();
	InsertNode(1,2);
	TraverseNode();
	return 0;
 } 

运行结果:
啊哈算法——第二章:栈队列与链表_第1张图片

你可能感兴趣的:(程序设计算法,链表,算法,数据结构)