/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: khoa.cpp
* Author: KHOA
*
* Created on August 26, 2016, 9:16 AM
*/
#include <iostream>
#include<stdio.h>
#include<stdio.h>
using namespace std;
struct Node {
int data;
Node *next;
};
struct List {
Node *head;
Node *tail;
};
// khoi tao stack
void Init(List &s) {
s.head = s.tail = NULL;
}
// kiem tra stack co rong khong
bool isEmpty(List &s) {
if (s.head == NULL) return true;
else return false;
}
// tao Node
Node *creat_Node(int x) {
Node *p = new Node;
if (p != NULL) {
p->data = x;
p->next = NULL;
} else return NULL;
}
// Push vao stack
void push(List &s, int x) {
Node *p = creat_Node(x);
if (isEmpty(s)) {
s.head = s.tail = p; // neu stack rong thi ta gan p la phan tu dau va cuoi
} else {
p->next = s.head; // cho phan tu ke tiep bang phan tu dau
s.head = p; // cap nhat phan tu dau la phan tu moi them vao
}
}
// Pop phan tu ra khoi stack
void pop(List &s) {
Node *p = s.head;
if (!isEmpty(s)) {
s.head = p->next;
delete p;
} else {
cout << "\nDanh sach da rong! ";
}
}
// tim kiem phan tu trong stack
Node *search_Node(List &s, int x) {
Node *q = s.head;
while (q != NULL) {
if (q->data == x) {
return q;
} else {
q = q->next;
}
}
return NULL;
}
// Nhap du lieu cho Stack
void nhap(List &s) {
int n;
cout << "nhap so luong phan tu cho stack: ";
cin>>n;
for (int i = 1; i <= n; i++) {
int x;
cout << "Phan tu " << i << ": ";
cin>>x;
push(s, x);
}
}
// xuat cac phan tu trong stack
void xuat(List &s) {
Node *p = s.head;
while (p != NULL) {
cout << " " << p->data;
p = p->next;
}
}
int main() {
List s;
Init(s);
nhap(s);
xuat(s);
int x;
int lc;
do {
cout << "\n_ _ _CHUONG TRINH STACK_ _ _";
cout << endl;
cout << " 1.Push Stack"
<< "\n 2.Pop Stack"
<< "\n 3.Tim phan tu"
<< "\n 4.Thoat";
cout << "\nNhap thong tin can kiem tra: ";
cin>>lc;
switch (lc) {
case 1: cout << "Nhap phan tu can Push: ";
cin>>x;
push(s, x);
break;
case 2: cout << "Pop phan tu trong Stack ";
pop(s);
cout << "\n";
break;
case 3: cout << "Nhap phan tu can tim kiem: ";
cin>>x;
if (search_Node(s, x) != NULL) cout << "Tim thay phan tu!\n";
else cout << "khong tim thay!\n";
break;
case 4: break;
default: cout << "Ban nhap sai ";
}
xuat(s);
cout << "\n";
} while (lc != 4);
return 0;
}
kkkk
Trả lờiXóasteresr
Trả lờiXóa