![](https://img.51dongshi.com/20250107/wz/18415992452.jpg)
在C++中,我們可以通過定義結構體來創建單鏈表。首先定義節點的結構體,如下所示:typedef struct node {char data[10]; // 定義結點的數據域為字符串struct node *next; // 結點的指針域} ListNode, *LinkList;接著定義結點總數的結構體:typedef struct nodetotal {int count; // 定義結點的數量struct node *next; // 首個結點的指針} NodeTotal, *SList;接下來,我們可以使用頭插入法來創建不帶頭結點的單鏈表。具體的函數實現如下:SList CreatListR2(void) {char ch[100];ListNode *s,*r;r = NULL;SList head=(SList)malloc(sizeof(NodeTotal)); // 生成結點統計head->count = 0;head->next = NULL;printf(" Input # to end !\n"); // 輸入"#"代表輸入結束printf(" Please input Node_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(" Please input Node_data: ");scanf("%s",ch);}printf("\n 利用頭插法建立單鏈表成功!\n")return head;}使用同樣的方法,我們可以創建一個帶頭結點的單鏈表。這里給出具體的實現代碼:LinkList CreatListR2(void) {char ch[100];ListNode *s,*r,*pp;LinkList head=NULL;printf(" Input # to end !\n"); // 輸入"#"代表輸入結束printf(" Please input Node_data: ");scanf("%s",ch);while(strcmp(ch,"#")!=0) {s=(ListNode *)malloc(sizeof(ListNode));strcpy(s->data,ch);s->next=head;head=s;printf(" Please input Node_data: ");scanf("%s",ch);}printf("\n 利用頭插法建立單鏈表成功!\n")return head;}同樣的,我們可以使用尾插入法來創建不帶頭結點的單鏈表。具體實現代碼如下:SList CreatListR1(void) {char ch[100];ListNode *s,*r;r = NULL;SList head=(SList)malloc(sizeof(NodeTotal)); // 生成結點統計head->count = 0;head->next = NULL;r=NULL;printf(" Input # to end !\n"); // 輸入"#"代表輸入結束printf(" Please input Node_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(" Please input Node_data: ");scanf("%s",ch);}printf("\n 利用尾插法建立單鏈表成功!\n")return head;}最后,使用尾插入法來創建一個帶頭結點的單鏈表。具體的實現代碼如下:LinkList CreatListR1(void) {char ch[100];ListNode *s,*r,*pp;LinkList head=NULL;r=NULL;printf(" Input # to end !\n"); // 輸入"#"代表輸入結束printf(" Please input Node_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(" Please input Node_data: ");scanf("%s",ch);}printf("\n 利用尾插法建立單鏈表成功!\n")return head;}