(Concatenating Lists) Write a program that concatenates two linked lists of char
ID: 3765921 • Letter: #
Question
(Concatenating Lists)
Write a program that concatenates two linked lists of characters. The
program should include function
concatenate
that takes pointers to both lists as arguments and
concatenates the second list to the first list.
Explanation / Answer
Program using visual studio #include #include struct list_el { char data; struct list_el * next; }; typedef struct list_el item; // Function prototypes void printList ( item * list ); void concatenate( item * list_A, item * list_B ); void main ( void ) { item * list1, * list2, * head; int i; head = NULL; // generate list of chars for(i = 74; i >= 65; i--) { list1 = (item *)malloc(sizeof(item)); list1->data = i; list1->next = head; head = list1; } head = NULL; // generate a second list of chars for(i = 84; i >= 75; i--) { list2 = (item *)malloc(sizeof(item)); list2->data = i; list2->next = head; head = list2; } printf( "The first list is: " ); printList( list1 ); printf( "The second list is: " ); printList( list2 ); printf( "List 2 concatenated to List 1 is: " ); concatenate( list1, list2 ); printList( list1 ); return 0; } void printList ( item * list ) { while(list!=NULL) { printf("%c ", list->data); list = list->next ; } printf( " " ); } void concatenate( item * list_A, item * list_B ) { while(list_A ->next != NULL) { list_A = list_A->next ; } list_A ->next = list_B ; /* set next address of last struct in list_A to the address of the beginning of list_B */ }Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.