單鏈表實現隊列的基本操作(入隊,出隊)

單鏈表實現隊列的基本操作(包括初始化隊列,入隊,出隊)


  1. 構造隊列結構體
struct node {
    int data;
    node *next;
};

struct queue {
    node *head, *tail;
};
  1. 隊列初始化
queue* create(queue *q) {
    q->head = new node;
    q->head->next = NULL;
    q->tail = q->head;
    return q;
}
  1. 插入隊列(尾插)
//插入時間複雜度o(1)
void push(queue *q, int value) {
	//尾插 
	node *ins = new node;
	ins->data = value;
	ins->next = q->tail->next;
	q->tail->next = ins;
	//移動尾指針 
	q->tail = ins;
}
  1. 出隊,(頭出)
//出隊時間複雜度o(1)
void pop(queue *q) {
	//頭出 
	if(q->head == q->tail) {
		cout<<"it is an empty queue!"<<endl;
		return;
	} else {
		node *temp = q->head->next;
		q->head->next = q->head->next->next;
		delete temp;
	}
}
  1. 遍歷隊列
void display (queue *q) {
	if (q->head == q->tail) {
		cout<<"it is an empty queue!"<<endl;
		return;
	} else {
		node *temp = q->head;
		while (temp->next) {
			cout<<temp->next->data<<endl;
			temp = temp->next;
		}
	}
}

主函數

int main() {
	//不是queue *q; 
	queue *q= new queue;
	q = create(q);
	
	//測試構建隊列和入隊
	int n;
	cin>>n;
	while (n-->0) {
		int value;
		cin>>value;
		push(q,value);
	}
	display(q);
	
	//出隊
	pop(q);
	display(q);
	return 0;
} 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章