在C++中,我们可以通过定义结构体来创建单链表。首先定义节点的结构体,如下所示:typedefstructnode{chardata[10];//定义结点的数据域为字符串structnode*next;//结点的指针域}ListNode,*LinkList;接着定义结点总数的结构体:typedefstructnodetotal{intcount;//定义结点的数量structnode*next;//首个结点的指针}NodeTotal,*SList;接下来,我们可以使用头插入法来创建不带头结点的单链表。具体的函数实现如下:SListCreatListR2(void){charch[100];ListNode*s,*r;r=NULL;SListhead=(SList)malloc(sizeof(NodeTotal));//生成结点统计head->count=0;head->next=NULL;printf("Input#toend!\n");//输入"#"代表输入结束printf("PleaseinputNode_data:");scanf("%s",ch);while(strcmp(ch,"#")!=0){s=(ListNode*)malloc(sizeof(ListNode));strcpy(s->data,ch);s->next=head->next;head->next=s;head->count++;printf("PleaseinputNode_data:");scanf("%s",ch);}printf("\n利用头插法建立单链表成功!\n")returnhead;}使用同样的方法,我们可以创建一个带头结点的单链表。这里给出具体的实现代码:LinkListCreatListR2(void){charch[100];ListNode*s,*r,*pp;LinkListhead=NULL;printf("Input#toend!\n");//输入"#"代表输入结束printf("PleaseinputNode_data:");scanf("%s",ch);while(strcmp(ch,"#")!=0){s=(ListNode*)malloc(sizeof(ListNode));strcpy(s->data,ch);s->next=head;head=s;printf("PleaseinputNode_data:");scanf("%s",ch);}printf("\n利用头插法建立单链表成功!\n")returnhead;}同样的,我们可以使用尾插入法来创建不带头结点的单链表。具体实现代码如下:SListCreatListR1(void){charch[100];ListNode*s,*r;r=NULL;SListhead=(SList)malloc(sizeof(NodeTotal));//生成结点统计head->count=0;head->next=NULL;r=NULL;printf("Input#toend!\n");//输入"#"代表输入结束printf("PleaseinputNode_data:");scanf("%s",ch);while(strcmp(ch,"#")!=0){s=(ListNode*)malloc(sizeof(ListNode));strcpy(s->data,ch);s->next=NULL;if(head->next==NULL)head->next=s;head->count++;if(r!=NULL)r->next=s;r=s;printf("PleaseinputNode_data:");scanf("%s",ch);}printf("\n利用尾插法建立单链表成功!\n")returnhead;}最后,使用尾插入法来创建一个带头结点的单链表。具体的实现代码如下:LinkListCreatListR1(void){charch[100];ListNode*s,*r,*pp;LinkListhead=NULL;r=NULL;printf("Input#toend!\n");//输入"#"代表输入结束printf("PleaseinputNode_data:");scanf("%s",ch);while(strcmp(ch,"#")!=0){s=(ListNode*)malloc(sizeof(ListNode));strcpy(s->data,ch);s->next=NULL;if(head==NULL)head=s;if(r!=NULL)r->next=s;r=s;printf("PleaseinputNode_data:");scanf("%s",ch);}printf("\n利用尾插法建立单链表成功!\n")returnhead;}