To add all elements of c list in t list | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

To add all elements of c list in t list

Write the statement how we can add

10th Dec 2020, 4:45 AM
Renu Kumari
Renu Kumari - avatar
2 Answers
0
#include <stdio.h> #include <stdlib.h> typedef struct Node { int value; struct Node *next; } Node; void push(Node **head, int data) { Node *tmp = (Node *)malloc(sizeof(Node)); tmp->value = data; tmp->next = (*head); (*head) = tmp; } int pop(Node **head) { Node *prev = NULL; int val; if (head == NULL) { exit(-1); } prev = (*head); val = prev->value; (*head) = (*head)->next; free(prev); return val; } Node *getLast(Node *head) { if (head == NULL) { return NULL; } while (head->next) { head = head->next; } return head; } void pushBack(Node *head, int value) { Node *last = getLast(head); Node *tmp = (Node *)malloc(sizeof(Node)); tmp->value = value; tmp->next = NULL; last->next = tmp; } void insert(Node *head, unsigned n, int val) { unsigned i = 0; Node *tmp = NULL; // Find last element. If there is list is empty // we will insert to end while (i < n && head->next) { head = head->next; i++; } tmp = (Node *)malloc(sizeof(Node)); tmp->value = val; // If it is not last element, next we will point to next element if (head->next) { tmp->next = head->next; // or to NULL } else { tmp->next = NULL; } head->next = tmp; } void fromArray(Node **head, int *arr, size_t size) { size_t i = size - 1; if (arr == NULL || size == 0) { return; } do { push(head, arr[i]); } while (i-- != 0); } void printLinkedList(const Node *head) { while (head) { printf("%d ", head->value); head = head->next; } printf("\n"); } void deleteList(Node **head) { Node *prev = NULL; while ((*head)->next) { prev = (*head); (*head) = (*head)->next; free(prev); } free(*head); } void appendList(Node **src, Node **dst) { if (src == NULL) { exit(-1); } while ((*src)->next != NULL) { pushBack(*dst, (*src)->value); (*src) = (*src)->next; } pushBack(*dst, (*src)->value); }
7th Feb 2023, 8:25 PM
Oleksandr Gorlinskyi
Oleksandr  Gorlinskyi - avatar
0
int main() { Node *head1 = NULL; Node *head2 = NULL; int arr1[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int arr2[] = {32, 16, 28, 36, 78, 3, 24, 7}; // Create two lists fromArray(&head1, arr1, sizeof(arr1) / sizeof(int)); fromArray(&head2, arr2, sizeof(arr2) / sizeof(int)); printf("Print values from the first list: "); printLinkedList(head1); printf("\n"); printf("Print values from the second list: "); printLinkedList(head2); printf("\n"); appendList(&head2, &head1); printf( "Print values from the first list after appending values form list 2: "); printLinkedList(head1); printf("\n"); deleteList(&head1); deleteList(&head2); }
7th Feb 2023, 8:25 PM
Oleksandr Gorlinskyi
Oleksandr  Gorlinskyi - avatar