Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- using namespace std;
- //dinh nghia 1 node. trong c++ chung ta khong can tu struct nua
- struct Node
- {
- int x;
- Node *pNext;
- };
- //1 list Lifo hay Fifo thi ta deu co the quan ly bang 2 con tro co ban nay. Nhu vay thao tac se de hon so voi 1 con tro first
- struct List
- {
- Node *pHead;
- Node *pTail;
- };
- //Khoi tao 1 List trong, khong co phan tu nao
- void CreateList(List &L)
- {
- L.pHead = L.pTail = NULL;
- }
- //Khoi tao 1 node co gia tri x
- Node *CreateNode(int x)
- {
- Node *p = new Node;
- //Kiem tra neu khong du bo nho de cap phat thi thoat luon
- if (p == NULL)
- exit(1);
- p->pNext = NULL;
- p->x = x;
- return p;
- }
- //Them 1 Node vao dau danh sach. cai nay danh cho LIFO
- void AddHead(List &L, Node *pAdd)
- {
- if (L.pHead == NULL)
- {
- L.pHead = L.pTail = pAdd;
- }
- else
- {
- pAdd->pNext = L.pHead;
- L.pHead = pAdd;
- }
- }
- //Them 1 Node vao cuoi danh sach. cai nay danh cho FIFO
- void AddTail(List &L, Node *pAdd)
- {
- if (L.pHead == NULL)
- {
- L.pHead = L.pTail = pAdd;
- }
- else
- {
- L.pTail->pNext = pAdd;
- L.pTail = pAdd;
- }
- }
- //Duyet cac phan tu trong List ra de xem
- void Output(List L)
- {
- Node *p = L.pHead;
- while (p != NULL)
- {
- cout << " " << p->x;
- p = p->pNext;
- }
- }
- //Doc tep vao danh sach FIFO
- void ReadFile(List &L)
- {
- //thay vi dung ifstream de doc minh dung lop tong quat hon la fstream va dung mode la ca in va out
- fstream f;
- int x;
- f.open("D:\\input.txt", ios::in | ios::out);
- if (!f)
- cout << "tep khong ton tai\n";
- else
- {
- while (!f.eof())
- {
- f >> x;
- //Tao node co gia tri x va them vao cuoi danh sach fifo
- AddTail(L, CreateNode(x));
- }
- }
- f.close();
- }
- //Lay phan tu chan duong trong fifo chuyen sang lifo
- void Fifo_Lifo(List Fifo, List &Lifo)
- {
- Node *p = Fifo.pHead;
- while (p != NULL)
- {
- if (p->x > 0 && p->x % 2 == 0)
- {
- //Tao node co gia tri p->x va them vao danh sach lifo
- AddHead(Lifo, CreateNode(p->x));
- }
- p = p->pNext;
- }
- }
- void main()
- {
- List Fifo, Lifo;
- //Khoi tao 2 list
- CreateList(Fifo);
- CreateList(Lifo);
- //Doc du lieu vao Fifo va xuat ra man hinh
- ReadFile(Fifo);
- Output(Fifo);
- cout << endl;
- //Doc du lieu vao Lifo va xuat ra man hinh
- Fifo_Lifo(Fifo, Lifo);
- Output(Lifo);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement