您的位置:首页 > 编程语言 > C语言/C++

单向链表之c++实现二

2012-12-07 23:32 239 查看
2012.12.07

前段时间学习数据结构的时候写了一个小例子,今天回头看看,真的是好傻,呵呵,是不是有同感呢,看自己以前写的代码都有种想屎的感觉。

领导说时间大把的,多想想多加一点功能吧,然后就给我说最好做一个一轮扫描完成后把所有的信息记录下来,以备以后上传数据库,该用何种结构记录数据呢,想了一下还是用自己还算熟悉的链表吧,于是翻出以前写的例子,不对啊'''''',以前的例子是这样的。

/article/11362338.html

这个例子是根据c语言书上的例子改编的,在创建链表时需要填冲数据,有删除节点,添加节点,输出链表功能。但这次我是要在mfc的界面下使用,按下按钮添加一次记录,记录添加到链表的最后一个节点,初始时需要一个空链表。对以上程序改进,写出如下代码:

/************************************************************************/

/* description:单向链表的c++实现

author: anderson

date: 2012.12.07 */

/************************************************************************/

#include "iostream.h"

typedef struct empty_list

{

int number;

struct empty_list *next;

}EMPTYLIST,*PEMPTYLIST;

class CEol

{

public:

PEMPTYLIST phead;

public:

CEol()

{

phead = NULL;

}

void CreateList()

{

phead = NULL;

cout<<"空链表创建成功!"<<endl;

}

void InsertNode(PEMPTYLIST pnewnode)

{

PEMPTYLIST p1;

p1 = phead;

if(phead == NULL)

{

phead = pnewnode;

pnewnode->next = NULL;

}

else

{

while(p1->next != NULL)

{

// p2 = p1;

p1 = p1->next;

}

p1->next = pnewnode;

pnewnode->next = NULL;

}

}

void PrintList()

{

PEMPTYLIST p;

// phead->number = 200;

p = phead;

while(p != NULL)

{

cout<<p->number<<" ";

p=p->next;

}

cout<<endl;

}

};

void main()

{

CEol eol;

//eol.CreateList();

cout<<"***********************************"<<endl;

PEMPTYLIST plist;

int count = 0;

cout<<"请输入要添加的内容:";

while(count<5)

{

plist =new EMPTYLIST;

cin>>plist->number;

// list.next = NULL;

// eol.phead = plist;

eol.InsertNode(plist);

cout<<"链表内容为:";

eol.PrintList();

count++;

}

/*

cout<<"plist1以输出"<<endl;

PEMPTYLIST plist2;

plist2 =new EMPTYLIST;

plist2->number = 200;

eol.InsertNode(plist2);

// cout<<eol.phead->number<<endl;

eol.PrintList();

cout<<"plist2以输出"<<endl;

PEMPTYLIST plist3;

plist3 =new EMPTYLIST;

plist3->number = 300;

eol.InsertNode(plist3);

// cout<<eol.phead->number<<endl;

eol.PrintList();

while(plist3->number != 0)

{

plist3 =new EMPTYLIST;

cin>>plist3->number;

eol.InsertNode(plist3);

// cout<<eol.phead->number<<endl;

eol.PrintList();

}

*/

}

首先定义一个结构体的指针phead,并赋为null,这样就算是是创建了一个空链表,然后就是在按一下按钮后,需要添加一个新的节点到末尾,每按一次,new 一empty_list,开辟一块存储空间用plist保存其地址,然后向这块地区写填充数据,填完后通过InsertNode把新添加的节点和原链表连接起来,ok啦,用PrintList看看是不是完成了预期结果

,(*^__^*) 嘻嘻……,用while循环来模拟点击按钮事件,这样就可以,下周就把这个运用到项目去,O(∩_∩)O哈!

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: