lap trinh c

danh sách liên kết

#include<iostream.h>

#include<conio.h>

#include<stdio.h>

struct NODE

{

    int Key;

    NODE *pNext;

};

NODE* CreateNode(int Data)

{

    NODE* pNode;

    pNode = new NODE;

    if(pNode== NULL)

        return NULL;

    pNode->Key = Data;

    pNode->pNext = NULL;

    return pNode;

}

int AddHead(NODE* &pHead, int Data)

{

    NODE *pNode;

    pNode = CreateNode(Data);

    if(pNode==NULL)

        return 0;

    if(pHead==NULL)

        pHead=pNode;

    else

    {

        pNode->pNext=pHead;

        pHead=pNode;

    }

    return 1;

}

void PrintList(NODE *pHead)

{

    NODE *pNode;

    pNode=pHead;

    while(pNode!=NULL)

    {

        printf("%5d",pNode->Key);

        pNode=pNode->pNext;        //

    }

}

void RemoveAll(NODE* &pHead)

{

    NODE *pNode;

    while(pHead !=NULL)

    {

        pNode=pHead;

        pHead=pHead->pNext;

        delete pNode;

    }

    pHead=NULL;

}

//int _tmain(int argc, _TCHAR* argv[])

void main()

{

    NODE *pRoot;

    pRoot=NULL;

    int Data;

        clrscr();

    do

    {

        printf("nhap vao du lieu, -1 de ket thuc:");

        scanf("%d",&Data);

        if(Data==-1)

            break;

        AddHead(pRoot,Data);

    }while(Data!=-1);

    printf("

Du lieu da dc nhap:

");

    PrintList(pRoot);

    RemoveAll(pRoot);

    getch();

}

các thuật toán sắp xếp

#include<iostream.h>

#include<conio.h>

int LinearExhaustive(int a[],int n,int x);

int LinearSentinel(int a[],int n,int x);

int BinarySearch(int a[],int n,int x);

void nhapmang(int a[],int &n);

void main()

{

    clrscr();

    int x,a[100],n;

    nhapmang(a,n);

    cout<<"nhap so can tim:";

    cin>>x;

    cout<<BinarySearch(a,n,x);

    //cout<<LinearSentinel(a,n,x);

    //cout<<LinearExhaustive(a,n,x);

    getch();

}

void nhapmang(int a[],int &n)

{

    int x;

    cout<<"nhap so luong mang:";

    cin>>n;

    for(int i=0;i<n;i++)

    {

        cin>>a[i];

    }

}

int LinearExhaustive(int a[], int n, int x)

{

    for(int i=0;i<n;i++)

    {

        if(a[i]==x)

        {

            return i;

        }

    }

    return -1;

}

int BinarySearch(int a[],int n,int x)

{

    int l=0,r=n-1;

    while(l<=r)

    {

        int m=(l+r) /2;

        if(a[m]==x)

        {

            return m;

        }

        else

        {

            if(x<a[m])

            {

                r=m-1;

            }

            else

            {

                l=m+1;

            }

        }

    }

    return -1;

}

int LinearSentinel(int a[],int n,int x)

{

    a[n]=x;

    for(int i=0; ;i++)

    {

        if(a[i]==x)

        {

        return i;

        }

    }

}

Bạn đang đọc truyện trên: truyentop.pro

Tags: