链表实例

链表图示:

/*
功能:创建个一链表,对这个链表进行遍历
日期:2012-10-5
说明:这个程序很重要,要看懂,对着图看
*/

# include <stdio.h>
# include <malloc.h>
# include <windows.h>

struct Node * create_list(void);
void traverse_list(struct Node *);
//bool empty_list(struct Node *);

//定义链表节点数据类型
struct Node
{
    int data; //数据域
    struct Node * pNext; //指针域
};

int main (void)
{
    struct Node * pHead =NULL; //pHead用来存放链表头结点地址
    pHead = create_list();
    traverse_list(pHead);
    
    return 0;
}

struct Node * create_list(void)
{
    int len; //用来存放有效节点个数
    int i;
    int val; //用来存放用户输入的结点值

    //分配了一个不存放有效数据的头结点
    struct Node * pHead=(struct Node *)malloc(sizeof(struct Node));
    if (NULL==pHead)
    {
        printf("分配失败,程序终止!\n");
        exit(-1);
    }

    struct Node * pTail = pHead;
    pTail->pNext = NULL;

    printf ("请输入你需要生成的链表节点的个数: len= ");
    scanf ("%d", &len);

    for (i=0;i<len ;i++ )
    {
        printf ("请输入第%d个节点的值: ", i+1);
        scanf ("%d", &val);

        struct Node * pNew = (struct Node *)malloc(sizeof(struct Node));
        if (NULL==pNew)
        {
            printf("分配失败,程序终止!\n");
            exit(-1);
        }

        pNew->data = val;
        pTail->pNext =pNew;
        pNew->pNext = NULL;
        pTail = pNew;
        
    }
    return pHead;        
}


/*
//判断链表是否为空
bool empty_list(struct Node * pHead)
{
    if (pHead->pNext == NULL) //pHead->pNext相当于(*pHead).Next
    {
        return true;
    }
    else 
    {
        return false;
    }
}
*/


void traverse_list(struct Node * pHead)
{
    struct Node * p = pHead->pNext;//指向首节点
    
    while (NULL!=p)
    {
        printf("%d\n",p->data);
        p = p->pNext;
    }
    return;
}

 

posted @ 2015-12-06 12:02  kennyhip  阅读(154)  评论(0编辑  收藏  举报