安全的建立单链表

#include<iostream>
#include <stdio.h>
#include <malloc.h>
using namespace std;

typedef struct ListTableCell
{
    char mdata[20];
     struct ListTableCell *next;
}LtCell;

LtCell *LTProductor(int ListLength){
    
    LtCell *headp,*pre,*nowptr;

    if ((headp= (LtCell*)malloc(sizeof(LtCell)))==NULL)  //这是内存检测的一步,很重要
    {
        cout<<"Some Memory is shortage!"<<endl;
        exit(0);
    }
    headp->next=NULL;
    headp->mdata[0]='/0';
    pre=headp;
    for (int i=0;i<ListLength;i++)              //用nowptr生成新的listcell,然后通过pre完成对链表的连接
    {
        if ((nowptr=(LtCell*)malloc(sizeof(LtCell)))==NULL)
        {
            cout<<"Memory is not enough for strage of new data"<<endl;
            exit(0);
        }

        pre->next=nowptr;                     //上一级连到下一级,注意第一次要返回的指针是nowptr,不是指向它的headp(pre)
        cout<<"Please input Data for list:"<<endl;
        //scanf("%s",nowptr->mdata);
        cin>>nowptr->mdata;                    //直接将输入数据地址赋给当前listcell的数据项

        pre=nowptr;                           //将上一级变成下一级,继续上面过程
    }
    headp=headp->next;                        //链表建立完了以后记得把
    pre->next=NULL;
    printf("head data is:%s",headp->mdata);
    return (headp);
}

int main(){

    LtCell *mListHead=NULL;
    int listnm;
    cout<<"Input the length of List:"<<endl;
    cin>>listnm;
    mListHead=LTProductor(listnm);

    system("pause");
    return 0;
}

posted @ 2013-04-05 17:16  追风筝的小蜗牛  阅读(62)  评论(0)    收藏  举报