Queue-Linked List Implementation【1月22日学习笔记】

点击查看代码
//Queue-Linked List Implementation
#include<iostream>
using namespace std;
struct node {
	int data;
	node* next;
};

node* front = NULL;
node* rear = NULL;//末指针·,则不用遍历整个链表,constant time

void Enqueue(int x) {
	node* temp = new node;
	temp->data = x;
	temp->next = NULL;

	if (front == NULL && rear == NULL) {//头末指针均空
		front = rear = temp;//注意赋值表达式
		return;
	}
	rear->next = temp;//先将末节点尾巴指向新节点
	rear = temp;//再将末指针指向新节点

}//时间复杂度:O(1)

void Dequeue() {
	if (front == NULL)  return;

	node* run = front;//头指针不为空时
	if (front == rear) {//头末指针重合时,只剩一个节点
		front = rear = NULL;//front和rear是全局变量,注意悬挂指针问题
		                    /*****跟头指针相关的节点操作必须单独讨论*****/
	}
	else {
		front = run->next;
	}
	delete run;
}//时间复杂度:O(1)

int Front() {
	if (front == NULL)   return;
	return front->data;
}

void Print() {
	node* run = front;
	while (run != NULL) {
		cout << run->data << " ";
		run = run->next;
	}
	cout << endl;
}

int main() {
	Enqueue(2); Print();
	Enqueue(4); Print();
	Enqueue(6); Print();
	Dequeue();  Print();
	Enqueue(8); Print();
}
	


posted @ 2024-01-22 11:20  bituion  阅读(11)  评论(0)    收藏  举报