How to Create Linked List in C/C++

Here is the Code to create linked list

#include <stdio.h>
#include <stdlib.h>

struct Node{
int data;
struct Node *next;
};

typedef struct Node *node;

node createNewNode(){
node temp;
temp = (node)malloc(sizeof(struct Node)); // allocate memory equal memory as the size using malloc()
temp->next = NULL;// make next point to NULL (suppose this as last node)
return temp;
}

node addNode(node head, int value){
node tmp,p;
tmp = createNewNode();
tmp->data = value;
if(head == NULL){
head = tmp;
}
else{
p = head;
while(p->next != NULL){
p = p->next;
}
p->next = tmp;
}
return head;
}

int main()
{
node head = NULL;
head = addNode(head,2);
head = addNode(head,3);
head = addNode(head,5);
head = addNode(head,8);
node p;
p = head;
while(p != NULL){
printf("%d\n",p->data);
p = p->next;
}

return 0;
}

Thanks for visiting my blog.

Comments

Popular posts from this blog

Third Equation of motion, How to implement using C language

Second Equation of motion, How to implement using C language

First Equation of motion, How to implement using C language