Overview
It's relatively simple, but remember to release the unused head node.
The code is:
1 //Connect the LLIST2 head node behind the LList1 tail node.2 void3 Combine (linklist lList1, linklist lList2) {4Linknode *lst01tail = LList1;//eventually point to the tail node of the lList1.5Linknode *tmp;//The head node temporarily pointing to the LList2 to release the head node of the LList2 table.6 while(lst01tail->next) {7Lst01tail = lst01tail->Next;8 }9 TenTMP =LList2; OneLst01tail->next = llist2->next;//the tail node of the LList1 connects to the LList2. A //releases the head node that releases the LList2 table. - Free (TMP); -TMP =NULL; theLlist1->data + = llist2->data;//modifies the length of the linked list. -}
Full code:
1#include <stdio.h>2#include <malloc.h>3 4 #defineFALSE 05 #defineTRUE 16 7typedefstructNode {8 intdata;9 structNode *Next;Ten } Linknode; One Atypedef Linknode *linklist; - - //Initializes a single-linked list with a head node based on the number of nodes specified. the linklist -InitintN) { -Linklist llist = (linklist) malloc (sizeof(structnode));//head node. -Llist->next = NULL;//initially, the linked list is empty. +Llist->data = n;//The head node stores the total number of elements. - if(!llist) { +printf"Out of memory!\n"); A returnFALSE; at } - inti; -Linknode *tail =llist; - for(i =0; I < n; i++) { -Linknode * nnew = (Linknode *) malloc (sizeof(structnode)); - if(!nnew) { inprintf"Out of memory!\n"); - returnFALSE; to } +Nnew->data = i +1;//assigns a value to the new node. - //re-specify the tail node. theTail->next =nnew; *Tail =nnew; $Nnew->next =NULL;Panax Notoginseng } - returnllist; the } + A //traverse all nodes of a single linked list. the void + Traverse (linklist llist) { -Linknode *node; $node = llist->next;//points to the first node at the beginning. $ while(node) { -printf"%d", node->data); -node = node->Next; the } -printf"\ n");Wuyi return; the } - Wu //Connect the LLIST2 head node behind the LList1 tail node. - void About Combine (linklist lList1, linklist lList2) { $Linknode *lst01tail = LList1;//eventually point to the tail node of the lList1. -Linknode *tmp;//The head node temporarily pointing to the LList2 to release the head node of the LList2 table. - while(lst01tail->next) { -Lst01tail = lst01tail->Next; A } + theTMP =LList2; -Lst01tail->next = llist2->next;//the tail node of the LList1 connects to the LList2. $ //releases the head node that releases the LList2 table. the Free (TMP); theTMP =NULL; theLlist1->data + = llist2->data;//modifies the length of the linked list. the } - in int theMainvoid) { the intn =3; AboutLinklist llist =init (n); theLinklist LList2 =init (n); the Traverse (llist); the Combine (llist, lList2); + Traverse (llist); -printf"\ n"); the}
C-Link two linked list