Linked list in C

      No Comments on Linked list in C

Linked list in C are implemented in structures. Linked list is implemented using pointers. The first node is called head

Linked list in C

Each node consist of two parts:

  • data
  • pointer to next node

//linked list in c
 struct Node
 {
   int data;
   struct Node *next;
 };

Creating first linked list

#include<stdio.h>
#include<stdlib.h>
struct Node
{
  int data;
  struct Node *next;
};
int main()
{
  struct Node *head=NULL;
  struct Node* first = NULL;
  struct Node* second = NULL;
   
  // allocate 3 nodes in the heap  
  head = (struct Node*)malloc(sizeof(struct Node)); 
  first = (struct Node*)malloc(sizeof(struct Node));
  second = (struct Node*)malloc(sizeof(struct Node));
  
  //assign data to head node
  head->data=1;
  head->next=first; 
  
  //assign data to first node
  first->data=2;
  first->next=second;
  
  //assign data to second node
  second->data=3;
  second->next=NULL;

  print(head);
  return 0;
}

Traversing a Linked List

void print(struct Node *n)
{
	while(n!=NULL)
	{	
	 printf("\n%d",n->data);
	 n=n->next;
	}
}

Inserting a Linked List

#include<stdio.h>
#include<stdlib.h>
struct Node
{
  int data;
  struct Node *next;
};
void print(struct Node *n)
{
	while(n!=NULL)
	{	
	 printf("\n%d",n->data);
	 n=n->next;
	}
}
void push(struct Node *pointer_to_head,int ndata)
{
	struct Node *new_node=(struct Node*)malloc(sizeof(struct Node));
	new_node->data=ndata;
	new_node->next=pointer_to_head;
	pointer_to_head->next=new_node;
}
int main()
{
  struct Node *head=NULL;
  struct Node* first = NULL;
  struct Node* second = NULL;
   
  // allocate 3 nodes in the heap  
  head = (struct Node*)malloc(sizeof(struct Node)); 
  first = (struct Node*)malloc(sizeof(struct Node));
  second = (struct Node*)malloc(sizeof(struct Node));
  
  //assign data to head node
  head->data=1;
  head->next=first; 
  
  //assign data to first node
  first->data=2;
  first->next=second;
  
  //assign data to second node
  second->data=3;
  second->next=NULL;
  
  print(head);
  push(head,7);
  print(head);
  return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *