Data structures in C, Series 1.1: Linked Lists
Adding element to a linked list in C by making a function Push();
We will make the head of the list global for easy access to all the function .
#do comment if any doubt
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node * next;
};
struct node * s;
void push()
{ struct node * temp,*cur;
temp = (struct node *)malloc(sizeof(struct node));
scanf("%d",&temp->data);
temp->next=NULL;
cur = s;
if(s == NULL)
{
s= temp;
}
else
{
while(cur->next != NULL)
{
cur = cur->next;
}
cur->next = temp;
}
printf("done ");
}
void printm()
{ struct node * temp = s;
while(temp!= NULL)
{
printf("%d>>",temp->data);
temp = temp->next;
}
printf("DONE");
}
int main()
{
s = (struct node *)malloc(sizeof(struct node));
s = NULL;
int h;
while(1){
printf("1 to push and 2 to print and 0 to exit");
scanf("%d",&h);
if(h ==1)
push();
if(h == 2)
printm();
if(h == 0)
break;
}
return 0;
}
We will make the head of the list global for easy access to all the function .
#do comment if any doubt
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node * next;
};
struct node * s;
void push()
{ struct node * temp,*cur;
temp = (struct node *)malloc(sizeof(struct node));
scanf("%d",&temp->data);
temp->next=NULL;
cur = s;
if(s == NULL)
{
s= temp;
}
else
{
while(cur->next != NULL)
{
cur = cur->next;
}
cur->next = temp;
}
printf("done ");
}
void printm()
{ struct node * temp = s;
while(temp!= NULL)
{
printf("%d>>",temp->data);
temp = temp->next;
}
printf("DONE");
}
int main()
{
s = (struct node *)malloc(sizeof(struct node));
s = NULL;
int h;
while(1){
printf("1 to push and 2 to print and 0 to exit");
scanf("%d",&h);
if(h ==1)
push();
if(h == 2)
printm();
if(h == 0)
break;
}
return 0;
}
Comments
Post a Comment