Hàng đợi Queue

mail@pastecode.io avatar
unknown
c_cpp
3 years ago
2.0 kB
2
Indexable
Never
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

// Tao cau truc Node giong DSLK
struct Node {
    int data;
    Node *Next;
};

// Tao cau truc Queue
struct Queue {
    Node *Head;
	Node *Tail;
};

// Ham khoi tao Queue
void init(Queue &Q) {
    Q.Head = Q.Tail = NULL;
}

// Ham khoi tao 1 Node
Node *taoNode(int x) {
    Node *p = (Node*) malloc(sizeof(Node));
    p->Next = NULL;
    p->data = x;
    return p;
}

// Ham them phan tu co gia tri x vao Queue [viet ham nay phai viet ham taoNode(int x) truoc no]
void push(Queue &Q, int x) {
	Node *p = taoNode(x);
    if(!Q.Head) 
		Q.Head = Q.Tail = p;
    else {
        Q.Tail->Next = p;
        Q.Tail = p;
    }
}

// Ham lay gia tri phan tu dau tien cua Queue
int getHead(Queue Q) {
    if(Q.Head)
        return Q.Head->data; // neu lay phan tu cuoi thi Q.Tail->data
    return -1;
}

// Ham xoa phan tu dau cua Queue
int Pop(Queue &Q) {
    if(Q.Head){
        Node *p = Q.Head;
        Q.Head = Q.Head->Next;
        return p->data;
        delete p;
    }
    return 0;
}

// Ham lay ra phan tu co gia tri x trong Queue
int getNode(Queue Q, int x) {
	Node *p = Q.Head;
	while(p) {
		if(p->data == x)
			return 1;
		p = p->Next;
	}
	return 0;
}

// Xuat toan bo Queue
void xuat(Queue Q) {
	printf("\nCac phan tu trong Queue: ");
    Node *p = Q.Head;
    while(p) {
        printf("%d ", p->data);
        p = p->Next;
    }
}

int main() {
	Queue Q; init(Q);
	
	int n;
	printf("Nhap so phan tu: "); scanf("%d", &n);
	
	while(n--) {
		int x;
		printf("Nhap phan tu: "); scanf("%d", &x);
		push(Q, x);
	}
	xuat(Q);
	// Lay ra phan tu dau tien cua Queue
	printf("Phan tu dau tien: %d\n", getHead(Q));
	
	// Tim xem co ton tai phan tu 'tim' hay khong
	int tim;
	printf("Nhap phan tu can tim: "); scanf("%d", &tim);
	if(getNode(Q, tim))
		printf("Tim thay!");
	else
		printf("Khong tim thay!");
}