[cpp] 5
Viewer
*** This page was generated with the meta tag "noindex, nofollow". This happened because you selected this option before saving or the system detected it as spam. This means that this page will never get into the search engines and the search bot will not crawl it. There is nothing to worry about, you can still share it with anyone.
- #include<stdio.h>
- #include<stdlib.h>
- #include<conio.h>
- // khai báo
- struct Node{
- int Data;
- struct Node *pNext;
- };
- typedef struct Node NODE;
- struct List{
- struct Node *pHead;//con trỏ đầu
- struct Node *pTail;// con trỏ cuối
- };
- typedef struct List LIST;
- // khởi tạo
- void Init(List &l){
- l.pHead = l.pTail =NULL;//khởi tạo danh sách rỗng
- }
- // Tạo NODE
- NODE* getNode(int x){
- // x là dữ liệu đưa vào Data.
- NODE *p;
- //Cấp phát bộ nhớ cho NODE
- p = (NODE *)malloc(sizeof(NODE));
- if(p == NULL){
- return NULL;
- }
- p->Data = x;// Lưu x vào Data
- p->pNext = NULL;//khởi tạo mối liên kết;
- return p;
- }
- // Thêm Node
- void addHead(LIST &l, NODE *p){ // Thêm vào đầu danh sách
- if(l.pHead==NULL){ // Danh sách rỗng
- // Phần tử p thêm vào cũng chính là đầu cũng là cuối
- l.pHead = l.pTail = p;
- }else{
- p->pNext = l.pHead;// Bắt đầu gán
- l.pHead = p;
- }
- }
- // Nhập dữ liệu
- void InPut(LIST &l){
- int n;
- printf("\nBan muon nhap bao nhieu NODE");
- scanf("%d",&n);
- Init(l);
- int i = 1;
- for(i; i <= n; i++){
- int x;
- printf("\nNhap du lieu:");
- scanf("%d",&x);
- NODE *p = getNode(x);// Đưa dữ liệu vào Node
- addHead(l,p); // Thêm p vào đầu danh sách
- }
- }
- // Xuất danh sách
- void OutPut(LIST &l){
- NODE *p = l.pHead;
- if(l.pHead == NULL) return;
- while(p != NULL){
- printf("%d\t",p->Data);
- p = p->pNext;
- }
- }
- //Đổi chỗ
- void hoanVi(int &a, int &b){
- int temp = a;
- a = b;
- b = temp;
- }
- //Sắp xếp
- void sort(LIST &l){
- NODE *p = l.pHead;
- NODE *q = p->pNext;
- for(p = l.pHead; p != l.pTail; p = p->pNext){ // p trỏ vào phần tử đầu danh sách,p chạy đến phần tử cuối danh sách
- for(q = p->pNext; q != NULL; q= q->pNext){ // q trỏ vào phần tử tiếp theo , q chạy đến null.
- if(p->Data < q->Data){ // sắp xếp giảm dần
- hoanVi(p->Data, q->Data);
- }
- }
- }
- }
- int main(){
- LIST l;
- InPut(l);
- printf("DS: \n");
- OutPut(l);
- sort(l);
- printf("\nDS sau xap xep:\n");
- OutPut(l);
- getch();
- return 0;
- }
Editor
You can edit this paste and save as new: