c++怎么创建链表?

热心网友

结合我写的一个程序,创建链表的思路是:先用指针f=new InNode 创建一个表头;然后,再定义一个指针,使它指向这个表头,用InNode* p=f这句就可以了;接着不断分配动态存储空间给指针p,动态分配用p=new InNode这一句,当然,(不断分配),这个过程要用循环来完成的。嘻嘻!我写了一个程序,我是在VSIUALC C++里运行的,它是ok的。你慢慢体会吧。# include# includestruct InNode{int data;InNode* next;};开始创建链表。////////////////////////////////////////////////////void creat(InNode* &f, int n){if(nx;f=new InNode;f-data=x;if(n==1) {f-next=NULL;return;}InNode* p=f;for(int i=0; inext=new InNode;p=p-next;cinx;p-data=x;}p-next=NULL;}输出已创建的链表。////////////////////////////////////////////////////void travel(InNode* f){while(f){coutdatanext;}coutn;creat(head, n); travel(head);} 。

热心网友

link stuc

热心网友

#includeclassnode{ *next;};classINnode{ (intx);/*只写了2个方法*/voiddisplay(); *head;classnode*p1,*p2;INnode(){head=NULL;}};voidINnode::insert(intx){if(head==NULL){head=newnode;head-data=x;head-next=NULL;}else{p1=head;while(p1-next!=ULL)p1=p1-next;p2=newnode;p1-next=p2;p2-data=x;p2-next=NULL;}}voidINnode::display(){p1=head;while(p1!=NULL){coutdata;p1=p1-next;}}intmain(){classINnode*np;np-insert(22);np-insert(2);/*。。。。。。。。。。*/np-display();return0;}。

热心网友

既然是C++创建链表,当然要用到类了,结构体(struct)相对于类来说,有很多缺点,具体你买一本数据结构书看一看就知道了。链表一般用两个类:classnode{//这是结点类 ();~node();Typeget(){//Type是你的节点数据类型returndata;} *next;}classlist{//这是游标类 ();~list();voidFirster();voidNext();TypeGetCurrent(); *first,*current,*last;}其实我这里写再多,都不如你直接买本数据结构(C++描述)看一看,用类建立链表需要一定C++基础,初学者一般都是在初始化时出现问题,比如:定义nodex;其实是调用node类的构建函数node(),你要在node()里给类里边的元素赋初值,node()是构建函数,可以有参数,可以重载,如果在没有给类里的数据赋值前就使用里边的数据,程序肯定会出错,我要说的就这么多了,再说下去要把整本文前几章都写下来~。

热心网友

C++创建和C一样先定义一个结构体struct link{int num;link* next;//指向下一个结构体的指针};