链表

全部代码

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

typedef struct node
{
    int nValue;
    struct node * pNext;
}MyList;

void CreateList(MyList **ppHead)
{
    MyList *pTemp = NULL;
    MyList *pTail = NULL;

    //the number of node
    int number;

    int i;

    //the value of node
    int value;

    assert(ppHead != NULL);

    printf("please input a number of the node :");
    scanf("%d", &number);

    for(i=0; i<number; ++i)
    {
        printf("please input the %d value of node :", i+1);
        scanf("%d", &value);

        pTemp = (MyList *)malloc(sizeof(MyList));
        if(NULL == pTemp)
        {
            printf("allocate space failed !\n");
            exit(-1);
        }
        pTemp->nValue = value;
        pTemp->pNext = NULL;

        //add node
        if(NULL == *ppHead)
        {
            *ppHead = pTemp;
        }
        else
        {
            pTail->pNext = pTemp;
        }
        pTail = pTemp;
    }
}

void Traverse(MyList *pHead)
{
    if(NULL == pHead)
    {
        printf("list is null\n");
        return;
    }

    while(pHead != NULL)
    {
        printf("%d ", pHead->nValue);
        pHead = pHead->pNext;
    }
}

//reverse traverse
void RecTraverse(MyList *pHead)
{
    if(NULL == pHead)
    {
        return;
    }

    RecTraverse(pHead->pNext);
    printf("%d ", pHead->nValue);
}

//the inversion of list
void Reverse(MyList **ppHead)
{
    MyList *p1 = NULL;
    MyList *p2 = NULL;
    MyList *p3 = NULL;

    assert(ppHead != NULL);

    if(NULL==*ppHead || NULL==(*ppHead)->pNext)
    {
        return;
    }

    p2 = *ppHead;
    p3 = p2->pNext;

    while(p3 != NULL)
    {
        //change direction
        p2->pNext = p1;

        //handle the next node
        p1 = p2;
        p2 = p3;
        p3 = p2->pNext;
    }
    p2->pNext = p1;

    *ppHead = p2;
}

int main(void)
{
    MyList *pHead = NULL;

    CreateList(&pHead);
    Traverse(pHead);
    printf("\n");

    RecTraverse(pHead);
    printf("\n");

    Reverse(&pHead);
    Traverse(pHead);
    printf("\n");

    RecTraverse(pHead);
    printf("\n");

    return 0;
}

 

posted @ 2017-10-31 11:00  c&z  阅读(181)  评论(0编辑  收藏  举报