知识虽然是书上的,但代码是一个字一个字自己敲的,保证正确! 以下是单链表创建、插入的简单实现,上代码
#include <cstddef> #include<malloc.h> #include <iostream> #define ElemType int #define Maxsize 20 using namespace std; typedef struct Lnode{ ElemType data; struct Lnode* link; //next linklist prt = link; }*LinkList; int Insert(Lnode *p,Lnode *addptr,ElemType item) //新数据插入到p后面,新节点名为next { //Lnode* temp; //声明temp是新加入节点的指针 //temp = (Lnode*)malloc(sizeof(Lnode)); if (addptr == NULL) return 0; else addptr->data = item; //item是新加入节点数据 addptr->link = p->link; //先连上旧后继 p->link = addptr; //再取代p的旧后继 //next = temp; return 1; } int main() { Lnode* headptr;//申请头节点指针L1 int adder = 314; headptr = (Lnode*)malloc(sizeof(Lnode)); Lnode* L1; L1 = (Lnode*)malloc(sizeof(Lnode)); //L1 = NULL; Insert(headptr, L1, adder); /*试验一下如何检验错误,在仅仅使用很初级的函数的情况下 //大家可略过不看这一段灰色字体 while (!Insert(headprt, L1, adder)) { cout << "error"; break; }//subfun return 0->error */ cout << "L1->data=" << L1->data<<endl; Lnode* L2; L2 = (Lnode*)malloc(sizeof(Lnode)); Insert(headptr, L2, 628); cout << "L2->data="<<L2->data<<endl; cout << "L2->link->data=" << L2->link->data << endl; }总结:书上的代码也不一定全对,还需要自己练习练习并做修改。