单链表

// List.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <vld.h>

using namespace std;
typedef struct _List
{
    int nData;
    struct _List*next;
};

void insertList(_List* pList, int nData)
{
    while (pList->next){
        pList = pList->next;
    }
    _List *p = new _List;
    p->nData = nData;
    p->next = NULL;
    pList->next = p;
}

void output(_List *pList)
{
    while (pList){
        cout<<pList->nData<<endl;
        pList = pList->next;
    }
    cout<<"//////////////////////////"<<endl;
}

void DeleteList(_List *pList)
{
    while (pList){
        _List *p = pList->next;
        delete pList;
        pList = p;
    }
}

void DeleteNode(_List *pList, int nPos)
{
    int i = 0;
    while (pList && i++ < nPos){
        if (i == nPos){
            _List *p = pList->next->next;
            delete pList->next;
            pList->next = p;
            break;
        }
        pList = pList->next;
    }
}

void SortList(_List *pList)
{
    while (pList){
        _List *p = pList->next;
        while (p){
            if (pList->nData < p->nData){
                int nTemp = pList->nData;
                pList->nData = p->nData;
                p->nData = nTemp;
            }
            p = p->next;
        }
        pList = pList->next;
    }
}

int _tmain(int argc, _TCHAR* argv[])
{
    _List *pList = new _List;
    pList->nData = 0;
    pList->next = NULL;
    insertList(pList, 1);
    insertList(pList, 2);
    insertList(pList, 3);
    insertList(pList, 4);
    insertList(pList, 5);
    insertList(pList, 6);
    insertList(pList, 7);
    insertList(pList, 8);
    insertList(pList, 9);
    insertList(pList, 10);
    output(pList);

    SortList(pList);
    output(pList);

    DeleteNode(pList, 3);
    output(pList);
    DeleteList(pList);


    return 0;
}

 

posted @ 2016-03-01 15:07  QQ76211822  阅读(122)  评论(0编辑  收藏  举报