#include <stdio.h> #include <stdlib.h> struct node { int data; struct node* next; }; void addNode(struct node** head_ref, int input) { //1 create temp node struct node* temp = (struct node*)malloc(sizeof(struct node)); //2 assign data to temp node temp->data = input; //3 temp node address should point to head_ref temp->next = (*head_ref); //4 move the head_ref to temp node (*head_ref) = temp; } void printNode(struct node* head) { if(head == NULL) { return; } printf("Data: %d , Next: %p \n", head->data, head->next); printNode(head->next); }; int main() { struct node* head = NULL; for(int i = 0; i < 5; i++) { addNode(&head, i); } printNode(head); return 0; };
Category Archives: Uncategorized
Create and Read LINKED LIST
#include <stdio.h> #include <stdlib.h> struct node { int data; struct node *addr; }; void generateData(struct node *head) { struct node *current = NULL; for(int i=0; i<5; i++) { current = (struct node *)malloc(sizeof(struct node)); current->data=i; current->addr=head; head=current; } while(head) { printf("%d \n", head->data); head=head->addr; } } int main() { struct node *head = NULL; generateData(head); return 0; }