Danh sách liên kết đơn( Đưa node cuối về đầu danh sách)

#include<iostream> using namespace std; /// tho tác tren danh sách liên k?t ??n struct node { int data; struct node *pnext; }; node* getnode(int x) { node *p = new node; if (p == NULL) { return NULL; } p->data = x; p->pnext = NULL; return p; } struct list { node *phead; node *ptail; }; void init(list &l) { l.phead = l.ptail = NULL; } void addhead(list &l,node *p) { if (l.phead == NULL) { l.phead = l.ptail = p; } else { p->pnext = l.phead; l.phead = p; } } void addtail(list &l,node *p) { if (l.phead == NULL) { l.phead = l.ptail = p; } else { l.ptail->pnext = p; l.ptail = p; //l.ptail->pnext = NULL; } } void nhap(list &l) { int chon; init(l); do { cout << "\n1.nhap"; cout << "\n0.Thoat"; cout << "\nNhap lua chon : "; cin >> chon; if (chon == 1) { int x; cout << "\nMoi nhap gia tri cho x: "; cin >> x; node *k = getnode(x); addtail(l, k); } } while (chon != 0); } void xuat(list l) { for (node *p = l.phead;p; p = p->pnext) { cout << p->data << " "; } } // hàm giải phóng bộ nhớ void giaiphong(list &l) { node *p=l.phead; while (p!=NULL) { node *g = l.phead; l.phead = l.phead->pnext; p=p->pnext; delete g; } } ////bây giờ ta làm câu đưa no de cuối về node đầu nhak void xoacuoi(list &l) { if (l.phead->pnext == NULL) { giaiphong(l); return; } node *j=new node; for (node *p = l.phead; p; p = p->pnext) { if (p == l.ptail) { l.ptail = j; l.ptail->pnext = NULL; addhead(l, p); return; } j = p; } } int main() { list l; nhap(l); xuat(l); xoacuoi(l); cout << endl; xuat(l); giaiphong(l); cout << "\nDanh sach sau khi giai phong la: "; xuat(l); system("pause"); return 0; }

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.