Simple and Basic Linked List in C

Here is A Simple Linked program implemented for stack. Well this is a very basic one to provide an idea to you. I will explain it in detailed when I get some time.

linkedlist

#include<stdio.h>
struct node{
int val;
struct node *next;
}*list;
struct node *head = NULL;
struct node *curr = NULL;
void insert(int value)
{
struct node *temp;
int i=0;
if(head == NULL)
{
temp = (struct node *)malloc(sizeof(struct node));
temp->val = value;
temp->next = NULL;
head = curr = temp;
}
else {
temp = (struct node *)malloc(sizeof(struct node));
temp->val=value;
temp->next=NULL;
curr->next=temp;
curr = temp;
}
}
void pop()
{
struct node *temp,*prev;
int entcount=0;
if(head == NULL)
{
printf("stack emptyn");
}
else {
temp = prev = head;
while(temp->next != NULL)
{
entcount++;
prev=temp;
temp=temp->next;
}
printf("deleting element: %dn", temp->val);
prev->next = NULL;
if(entcount == 0)
curr = head = NULL;
else curr = prev;
free(temp);
}
}
void display()
{
struct node *temp = head;
int i=0;
if(head == NULL)
printf("Stack is emptyn");
else {
printf("n");
while(temp != NULL)
{
printf("%dt", temp->val);
temp = temp->next;
}
printf("n");
}
}
int main()
{
int choice, value;
while(1)
{
printf("Enter your choice 1.Push 2.Pop 3.Display 4.Exitt:");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter the value to insert: ");
scanf("%d",&value);
insert(value);
break;
case 2:
pop();
break;
case 3:
display();
break;
default:
exit(0);
}
}
return 0;
}

Add a Comment

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