#include <stdio.h>#include <stdlib.h>struct Node { char data; struct Node* next;};void print(struct Node* n){ while (n != NULL) { printf(" %c ", n->data); n = n->next; } printf("\n");}// this function will add new node in the beginning of thelistvoid push(struct Node** head_ref, char new_data){ //allocate a memory for new node struct Node *new_node=(struct Node *)malloc(sizeof(structNode));
// insert data in the new Node new_node->data=new_data; // make the new node points to head new_node->next=(*head_ref); //make the new node as head (*head_ref)=new_node;
} void append(struct Node** head_ref, int new_data){ /* 1. allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(structNode));
struct Node *last = *head_ref; /* 2. put in the data */ new_node->data = new_data;
/* 3. This new node is going to be the last node, so makenext of it as NULL*/ new_node->next = NULL;
/* 4. If the Linked List is empty, then make the new nodeas head */ if (*head_ref == NULL) { *head_ref = new_node; return; }
/* 5. Else traverse till the last node */ while (last->next != NULL) last = last->next;
/* 6. Change the next of last node */ last->next = new_node; return;} int main(){ struct Node* head = NULL; struct Node* second = NULL;
// allocate 2 nodes in the heap head = (struct Node*)malloc(sizeof(struct Node)); second = (struct Node*)malloc(sizeof(struct Node));
head->data = 'A'; // assign data in first node head->next = second; // Link first node with // the second node
// assign data to second node second->data = 'B';
// Link second node with the third node second->next = NULL;
print(head); append(&head,'C'); push(&head,'g'); print(head);
return 0;}
In C Code Please
Questions are in the code /* 1 */, /* 2 */ and so on...
#include #include struct Node { char data; struct Node* next; }; void print(struct Node* n) { wh
-
- Site Admin
- Posts: 899603
- Joined: Mon Aug 02, 2021 8:13 am