Hey guys...After thinking so much i thought why not to start with the basics of DS 1st.So,here is the 1st code about a singly linked list.The code is simply illustrating how we can add and display some nodes in a singly linked list.I hope the beginners mainly confuse in this code when they see the symbol **.That's preety common.** is nothing but pointer to a pointer.I assume that you have knowledge about pointers.
Pointers basically point to some memory location.
Eg.-int a=10;
int *p=&a;
Here p stores the address of variable a ie some hexadecimal value or something.
*p refers to the value stored at a ie 10.
Now if we want to store the address of pointer p then we can't declare the pointer as
int *q=&p; //Wrong...
We will have to declare as
int **q=&p;
So i think now you may be clear about **.If we wish to change the value pointed by a pointer then we will have to pass the address of that pointer as pointer to pointer argument.That is what we are doing here.
Here we want to change the value pointed by the start pointer of struct node via the append function in the 1st calling when there is no node added in the linked list.See code of append funcn below:
if(*ps==NULL)
{
*ps=temp1;
return;
}
So,We pass the address of start pointer in the function append.In display funcn we don't want to change anything but just traverse the linked list.So,we just pass the start pointer.
//My first linked list code...It's just a beggining...:)
#include<stdio.h>
#include<stdlib.h>
//A linked list node has two parts.Data part contains the value to be stored in linked list and The next pointer points to the next node of linked list.If there is nothing to point to the next pointer holds NULL.
struct node
{
int data;
struct node *next;
};
void append(struct node **,int);
void display(struct node *);
int main()
{
struct node *start=NULL;
append(&start,15);
append(&start,10);
append(&start,25);
append(&start,5);
append(&start,16);
append(&start,22);
append(&start,24);
append(&start,8);
append(&start,31);
append(&start,12);
display(start);
return 0;
}
void append(struct node **ps,int x)
{
struct node *temp,*temp1;
temp1=(struct node *)malloc(sizeof(struct node));
temp1->data=x;
temp1->next=NULL;
if(*ps==NULL)
{
*ps=temp1;
return;
}
temp=*ps;
while(temp->next!=NULL)
temp=temp->next;
temp->next=temp1;
}
void display(struct node *ps)
{
while(ps!=NULL)
{
printf("%d\n",ps->data);
ps=ps->next;
}
}
No comments:
Post a Comment