You are on page 1of 39

LINKED LISTS

List is a ordered collections of objects. The linked list is a data structure which consists of a series
of structures, which are not necessarily adjacent in memory. Each structure contains the data and a pointer
to a structure containing its successor. We call this the next pointer. The last cell's next pointer points to
NULL

Arrays
 In an array each node (element) follows the previous one physically (i.e. contiguous spaces in the
memory)
 Arrays are fixed size: either too big (unused space ) or not big enough (overflow problem)
 Maximum size of the array must be predicted which is sometimes not possible.
 Inserting and deleting elements into an array is difficult. Have to do lot of data movement, if in array
of size 100, an element is to be inserted after the 10th lement, then all remaining 90 have to be shifted
down by one position.

Linked Lists
 Linked lists are appropriate when the number of data elements to be represented in the data structure
are not known in advance.
 Linked lists are dynamic, so the length of a list can increase or decrease as necessary.
 A linked list is a collection of nodes, each node containing a data element.
 Each node does not necessarily follow the previous one physically in the memory.
 Nodes are scattered at random in memory.
 Insertion and Deletion can be made in Linked lists, by just changing links of a few nodes, without
disturbing the rest of the list. This is the greatest advantage.
 But getting to a particular node may take large number of operations.
 Every node from start needs to be traversed to reach the particular node.

Types:
 Single linked list
 Circular linked list
 Doubly linked list

Single linked list :

Node structure:
A node in a linked list is a structure that has at least two fields. One of the fields is a data field; the
other is a pointer that contains the address of the next node in the sequence.

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

The pointer variable next is called a link. Each structure is linked to a succeeding structure by way
of the field next. The pointer variable next contains an address of the location in memory of the successor
structnode element or the special value NULL.

Linked
list with actual pointer values

More examples of Nodes:


1. A node with one data field:

struct node
{
int number;
struct node * link;
};

2. A node with 3 data fields:

struct student
{
char name[20];
int id;
double grdPts;
struct student *next_student;
};

3. A structure in a node:

struct person
{
char name[20];
char address[30];
char phone[10];
};
struct person_node
{
struct person data;
struct person_node *next;
};

A simple Linked List:

• The head pointer addresses the first node of the list, and each node points at its successor node.
• The last node has a link value NULL.

Empty List:

Empty Linked list is a single pointer having the value of NULL.


pHead = NULL;

Basic Linked List Operations:


1. Add a node
2. Delete a node
3. Looking up a node
4. List Traversal (e.g. Counting nodes)

1. Add a Node:
There are four steps to add a node to a linked list:
1. Allocate memory for the new node.
2. Determine the insertion point (you need to know only the new node’s predecessor)
3. Point the new node to its successor.
4. Point the predecessor to the new node.

E.g. adding Two nodes to an Empty List:

To form linked list which contains two integers 39 and 60, first define a structure to hold two pieces
of information in each node- an integer value, and the address corresponding to the next structure of same
type.

struct node
{
int data;
struct node *next;
};
struct node *pNew, *pHead;
Use malloc to fetch one node from the memory, and let pNew point to this node.

pNew = (struct node *) malloc(sizeof(struct node));


pHead = NULL;

Now to store 39 in the data part of the node, we can use


(*pNew).data = 39;

A more convenient way is to use the notation


pNew->data = 39;
pNew->next = NULL;

At this moment there are no elements in the list. Pointer pHead points to NULL.
First element 39 is stored in node pNew. So make it the head node.

pNew->next = pHead;
/* set link to NULL*/
pHead = pNew;
/* point list to first node*/

Now we have got one node in the list, which is being pointed to by pHead. To put the next value
60 on the list, we must use malloc to fetch another node from the memory.

pNew = (struct node *) malloc(sizeof(struct node));

Let us now assign the data value to this node:


pNew->data = 60;
pNew->next = NULL;

Now we need to link this new node to the pHead node, which can be done by following
statement:
pHead->next = pNew;

This gives us the list of two nodes:

Add a node at the end of the list:


Given the list pHead

let us say we are interested in adding a node containing 90 at the end of this list. As a first step, use
malloc to get a new node pNew from the memory and load 90 in the data field and NULL in the next field.

pNew->data = 90;
pNew->next = NULL;

Now, the last node containing 80 would become the predecessor of the node containing
90 after the node is added. Let us call this node as pPre.

Use a temporary variable pPre and initialize it to pHead. Now hop through the nodes till you get a node
whose next link is NULL. Then pPre will be pointing to the last node.

pPre = pHead;
while ( pPre->next != NULL )
pPre = pPre->next;

Now link pPre with pNew .

pPre->next = pNew;

This would result in the node pNew to be attached to the list as the last node.

Inserting a node in a Linked List: (General case)

Insertion into a linked list

So far we have been discussing separate codes for inserting a node in the middle, at the end or at front of a
list. We can combine all the codes and write a general code for inserting a node anywhere in the list. Given
the head pointer (pHead), the predecessor (pPre) and the data to be inserted (item), we first allocate memory
for the new node (pNew) and adjust the link pointers.
struct node
{
int data;
struct node *next;
};
struct node *pHead;
pHead=NULL:

void insert_begin(int val)


{
struct node *pNew;
pNew = (struct node *)malloc(sizeof(struct node));
pNew->data = val;

if (pHead == NULL)
{
/*Adding to empty list*/
pHead = pNew;
pHead->next= NULL;
}
else
{
/* Adding as first node*/
pNew->next = pHead;
pHead = pNew;
}
}

void insert_last(int val)


{
struct node *pNew, *pTemp;
pNew = (struct node *)malloc(sizeof(struct node));
pNew->data = val;
pNew->next= NULL;

if (pHead == NULL)
{
/*Adding to empty list*/
pHead = pNew;
pHead->next= NULL;

}
else
{
/* Adding as last node*/
pTemp = pHead;
while(pTemp->next!=NULL)
pTemp = pTemp->next;
pTemp->next = pNew;
pNew->next = NULL;
}
}

Insertion a node into single link List( General case)

void insert_between(int val)


{
struct node *pNew, *pPre, *pTemp;
int key;

printf(“Enter the value after which node to be inserted”);


scanf(“%d”, &key);

// Allocate memory for the new node


pNew = (struct node *)malloc(sizeof(struct node));
pNew->data = val;
pNew->next = NULL;

if (pHead == NULL) /*Adding to empty list*/

{
pHead = pNew;
pHead->next= NULL;
}

else
{
pTemp = pHead; /* Searching insertion point*/
while(pTemp!=NULL)
{
if(pTemp->data == key)
break;
else
{
pPre = pTemp;
pTemp = pTemp->next;
}
}

if( pTemp==NULL)
printf(“ The insertion point can’t be found\n”);
else
{
if ( pTemp==pHead) // inserted before head node
{
pNew->next = pTemp;
pHead = pNew;
}
else // insert as intermediate or last node
{
pNew->next = pTemp->next;
pTemp->next = pNew;
}
}
}
}

2. Delete a node:
Deleting a node requires that we logically remove the node from the list by changing various link pointers
and then physically deleting the node from the heap.
We can delete
• the first node
• any node in the middle
• the end node

To logically delete a node:


1. first locate the node itself , name the current node as pTemp and its predecessor node as
pPre.

2. change the predecessor’s link field to point to successor of the current node.

3. recycle the node (send it back to memory) using free.

void delete (int key, struct node *pHead)


{
struct node *pTemp, *pPre;
pTemp=pHead;

if (pHead == NULL)
printf(“ Empty linked list\n”);;
else // Search node
{
pTemp = pHead;

while (pTemp!=NULL)
{
if(pTemp->data == key)
break;
else
{
pPre = pTemp
pTemp = pTemp->next;
}
}

if( pTemp==NULL)
printf(“Node not found\n”);
else
{
if ( pTemp == pHead )
pHead = pTemp->next;
else
pPre->next = pTemp->next;
free(pTemp)
printf(“Node deleted\n” );
}
}
}

3. Search for an item in the list:

/* Given the item and the pointer to the head of the list, the function returns a pointer to
the node which matches the item, or returns NULL if the item is not found
*/
Struct node *Search (int item, struct node *pHead)
{
struct node *pTemp;
int i=1;
pTemp=pHead;
if (pHead == NULL)
printf(“ Empty linked list\n”);;
else // Search node
{
pTemp = pHead;
while (pTemp!=NULL)
{
if(pTemp->data == key)
break;
else
{
pTemp = pTemp->next;
i = i+1;
}
}

if( pTemp==NULL)
printf(“Node can’t be found\n”);
else
printf(“Node found at location %d\n”, i );
}
return(pTemp)
}

4. Counting the nodes in a List:

int count(struct node *pHead)


{
struct node * pTemp;
int c = 0;
pTemp = pHead;
while (pTemp != NULL)
{
c = c + 1;
pTemp = pTemp->next;
}
return c;
}

5. Printing the contents of a list:


To print the contents, traverse the list from the head node to the last node.

void display( struct node *pHead)


{
struct node *pTemp;
pTemp = pHead;

while (pTemp != NULL)


{
printf(“%d”, pTemp -> data);
pTemp = pTemp -> next;
}
}
/* PROGRAM FOR IMPLEMENTATION OF SINGLE LINKED LIST */

#include"stdio.h"
#include<alloc.h>
#define NULL 0

/* STRUCTURE CONTANING A DATA PART AND A LINK PART */

struct node
{
int data;
struct node *next;
}*pHead;

/* phead is a global pointer contains the adress of the first node in


list*/
pHead=NULL;

/* THIS IS THE MAIN PROGRAM */


main()
{
int i, num, loc;

while(1) /* this is an indefinite loop */


{
printf(" \n1.INSERT A NUMBER AT BEGINNING;\n");
printf(" 2.INSERT A NUMBER AT LAST:\n");
printf(" 3.INSERT A NUMBER AT A PARTICULAR LOCATION IN
LIST:\n");
printf(" 4.PRINT THE ELEMENTS IN THE LIST :\n");
printf(" 5.PRINT THE NUMBER OF ELEMENTS IN THE LIST\n");
printf(" 6.DELETE A NODE IN THE LINKED LIST:\n");
printf(" 7.GET OUT OF LINKED LIST:\n");
printf(" PLEASE, ENTER THE NUMBER:\n");
scanf("%d",&i); /* ENTER A VALUE FOR SWITCH */

switch(i)
{
case 1:
printf("ENTER THE NUMBER :-");
scanf("%d",&num);
insert_begin(num);
break;
case 2:
printf("ENTER THE NUMBER :-");
scanf("%d",&num);
insert_last(num);
break;
case 3:
printf(" PLEASE ENTER THE NUMBER :-");
scanf("%d",&num);
printf("PLEASE ENTER THE LOCATION NUMBER :-");
scanf("%d",&loc);
insert_after(num,loc);
break;
case 4:
printf(" THE ELEMENTS IN THE LIST ARE : ");
display( );
break;
case 5:
printf(" Total No Of Elements In The List
are%d",count());
break;
case 6:
printf(" PLEASE ENTER A NUMBER to be deleted :");
scanf("%d",&num);
delete(num);
break;
case 7:
exit();

} /* end if switch */
} /* end of while */
} /* end of main */

/* ADD A NEW NODE AT BEGINNING */


void insert_begin(int val)
{
struct node *pNew;
pNew = (struct node *)malloc(sizeof(struct node));
pNew->data = val;

if (pHead == NULL)
{
/*Adding to empty list*/
pHead = pNew;
pHead->next= NULL;

}
else
{
/* Adding as first node*/
pNew->next = pHead;
pHead = pNew;
}
}

/*THIS FUNCTION ADDS A NODE AT THE LAST OF LINKED LIST */


void insert_last(int val)
{
struct node *pNew, *pTemp;
pNew = (struct node *)malloc(sizeof(struct node));
pNew->data = val;
pNew->next= NULL;

if (pHead == NULL)
{
/*Adding to empty list*/
pHead = pNew;
pHead->next= NULL;

}
else
{
/* Adding as last node*/
pTemp = pHead;
while(pTemp->next!=NULL)
pTemp = pTemp->next;
pTemp->next = pNew;
pNew->next = NULL;
}
}

/*THIS FUNCTION DELETES A NODE */

void delete (int key, struct node *pHead)


{
struct node *pTemp, *pPre;
pTemp=pHead;

if (pHead == NULL)
printf(“ Empty linked list\n”);;
else // Search node
{
pTemp = pHead;

while (pTemp!=NULL)
{
if(pTemp->data == key)
break;
else
{
pPre = pTemp
pTemp = pTemp->next;
}
}

if( pTemp==NULL)
printf(“Node not found\n”);
else
{
if ( pTemp == pHead )
pHead = pTemp->next;
else
pPre->next = pTemp->next;

free(pTemp)
printf(“Node deleted\n” );
}
}
}

/* ADD A NEW NODE AFTER A SPECIFIED NO OF NODES */


insert_after(int num, int loc)
{
int i;
struct node *pNew,*pPre,*pTur;
pTemp=phead; /* here pTemp stores the first location */

if(loc > count()+1 || loc <= 0)


{
printf(" insertion is not possible : ");
return;
}

if (loc == 1) /* if list is null then add at beginning */


{
insert_begin(num);
return;
}
else
{
for(i=1;i<loc;i++)
{
ppre=pcur; /* ppre will be holding previous value */
pcur=pcur->next;
}
pnew=(struct node *)malloc(sizeof(struct node));
pnew->data=num;
pnew->next=ppre->next
ppre->next=pnew;

return;
}
}

// ADD A NEW NODE AFTER A SPECIFIED node value */


void insert_byValue(int val)
{
struct node *pNew, *pPre, *pTemp;
int key;

printf(“Enter the value after which node to be inserted”);


scanf(“%d”, &key);

// Allocate memory for the new node


pNew = (struct node *)malloc(sizeof(struct node));
pNew->data = val;

if (pHead == NULL) /*Adding to empty list*/

{
pHead = pNew;
pHead->next= NULL;
}

else
{
pTemp = pHead; /* Searching insertion point*/
while(pTemp!=NULL)
{
if(pTemp->data == key)
pNew->next = pTemp->next;
pTemp->next = pNew
else
{
pPre = pTemp;
pTemp = pTemp->next;
}
}

if( pTemp==NULL)
printf(“ The insertion point can’t be found\n”);
else
{
if ( pTemp==pHead) // inserted before head node
{
pNew->next = pTemp;
pTemp->next = pNew;
}
else // insert as intermediate or last node
{
pNew->next = pTemp->next;
pTemp->next = pNew;
}
}
}
}
/* THIS FUNCTION DISPLAYS THE CONTENTS OF THE LINKED LIST */
void display( )
{
struct node *pTemp;
pTemp=pHead;
if(pTemp ==NULL)
{
printf("NO ELEMENT IN THE LIST :");
return;
}
else /* traverse the entire linked list */
while(pTemp!=NULL)
{
printf("%d \n",r->data);
pTemp = pTemp ->next;
}
}

//THIS FUNCTION COUNTS THE NUMBER OF ELEMENTS IN THE LIST

void count()
{
struct node *pTemp;
int c=0;
*pTemp=phead;
while(pTemp!=NULL)
{
pTemp = pTemp ->next;
c++;
}
return(c);
}

Application of single linked list:

Program to add two polynomials:


e.g (6X2+3X+1) + (5X3+5X+3) = 5X3+6X2+8X+4

#include<stdio.h>
#include<alloc.h>
#include<conio.h>

struct node
{
int coeff;
int pow;
struct node *next;
};

struct node *poly1=NULL,*poly2=NULL,*poly=NULL;

void create(struct node *n)


{
char ch;
do
{
printf("\n enter coeff:");
scanf("%d",&node->coeff);
printf("\n enter power:");
scanf("%d",&node->pow);
node->next=(struct link*)malloc(sizeof(struct link));
node=node->next;
node->next=NULL;
printf("\n continue(y/n):");
ch=getch();
}
while(ch=='y' || ch=='Y');
}

void show(struct link *n)


{
while(n->next!=NULL)
{
printf("%dx^%d",n->coeff,n->pow);
n=n->next;
if(n->next!=NULL)
printf("+");
}
}

void polyadd(struct node *poly1,struct node *poly2,struct node *poly)


{
while(poly1->next && poly2->next)
{
if(poly1->pow>poly2->pow)
{
poly->pow=poly1->pow;
poly->coeff=poly1->coeff;
poly1=poly1->next;
}
else if(poly1->pow<poly2->pow)
{
poly->pow=poly2->pow;
poly->coeff=poly2->coeff;
poly2=poly2->next;
}
else
{
poly->pow=poly1->pow;
poly->coeff=poly1->coeff+poly2->coeff;
poly1=poly1->next;
poly2=poly2->next;
}
poly->next=(struct node *)malloc(sizeof(struct node));
poly=poly->next;
poly->next=NULL;
}

while(poly1->next || poly2->next)
{
if(poly1->next)
{
poly->pow=poly1->pow;
poly->coeff=poly1->coeff;
poly1=poly1->next;
}

if(poly2->next)
{
poly->pow=poly2->pow;
poly->coeff=poly2->coeff;
poly2=poly2->next;
}

poly->next=(struct node *)malloc(sizeof(struct node));


poly=poly->next;
poly->next=NULL;
}
}

main()
{
char ch;

poly1=(struct link *)malloc(sizeof(struct link));


poly2=(struct link *)malloc(sizeof(struct link));
poly=(struct link *)malloc(sizeof(struct link));

printf("\nenter 1st number:");


create(poly1);
printf("\nenter 2nd number:");
create(poly2);
printf("\n1st Number:");
show(poly1);
printf("\n2nd Number:");
show(poly2);
polyadd(poly1,poly2,poly);
printf("\nAdded polynomial:");
show(poly);
getch();
}
CIRCULAR LINKED LIST:
The circular linked list is similar to single linked list except that the last node’s next pointer points
to the first node.

In a circularly linked list, all nodes are linked in a continuous circle, without using null.

Various operations that can be performed with circular linked list are
 Creation of circular linked list
 Insertion of a node in circular linked list
 Deletion of any node from the list
 Display of circular linked list

//Circular Linked List in C

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<alloc.h>
#define NULL 0

struct node
{
int data;
struct node *next;
};
struct node *pHead;

void main()
{
int ch,n,m,key,i,cou
pHead = NULL;
while(1)
{
printf(" 1. CREATE A LIST \n”);
printf(" 2.INSERT A NUMBER AT BEGINNING;\n");
printf(" 3.INSERT A NUMBER AT LAST:\n");
printf(" 4.INSERT A NUMBER AFTER A PARTICULAR VALUE IN LIST:\n");
printf(" 5.DELETE A NODE IN THE LINKED LIST:\n");
printf(" 6.PRINT THE ELEMENTS IN THE LIST :\n");
printf(" 7.PRINT THE NUMBER OF ELEMENTS IN THE LIST\n");
printf(" 8.GET OUT OF LINKED LIST:\n");
printf(" PLEASE, ENTER THE NUMBER:\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("enter no of items");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("enter the element");
scanf("%d",&m);
create(m);
}
break;
case 2:
printf("enter the element");
scanf("%d",&m);
insert_begin(m);
break;
case 3:
printf("enter the element");
scanf("%d",&m);
insert_last(m);
break;
case 4:
printf("enter the element");
scanf("%d",&m);
printf("enter the value after which you want to insert");
scanf("%d",&key);
insert_after(m,key);
break;
case 5:
printf("Enter the element to delete");
scanf("%d",&m);
delete(m);
break;
case 6:
display();
break;
case 7:
cou=count();
printf("No. of elements in the list%d ", cou);
break;
case 8:
exit(0);
break;
default:
printf("wrong choice");
}
}
}

// Function to create circular list


create(int data)
{
struct node *pNew,*pTemp;
pNew =(struct node *)malloc(sizeof(struct node));
pNew ->data=data;
pNew ->next=NULL;

if(pHead == NULL)
{
pHead = pNew;
pNew ->next= pHead;
}
else
{
pTemp = pHead;
while(pTemp->next!=pHead)
pTemp = pTemp->next;
pTemp->next = pNew;
pNew->next = pHead;
}
return;
}

/* ADD A NEW NODE AT BEGINNING */


insert_begin(int val)
{
struct node *pNew, *pTemp;
pNew = (struct node *)malloc(sizeof(struct node));
pNew->data = val;
if (pHead == NULL)
{
/*Adding to empty list*/
pHead = pNew;
pHead->next= pNew;
printf("Node inserted\n");
}
else
{
/* Adding as first node*/
pTemp = pHead;
while(pTemp->next!=pHead)
pTemp = pTemp->next;
pTemp->next = pNew;
pNew->next = pHead;
pHead = pNew;
printf("Node inserted\n");
}
return;
}

/*THIS FUNCTION ADDS A NODE AT THE LAST OF LINKED LIST */


insert_last(int val)
{
struct node *pNew, *pTemp;
pNew = (struct node *)malloc(sizeof(struct node));
pNew->data = val;

if (pHead == NULL)
{
/*Adding to empty list*/
pHead = pNew;
pHead->next= pHead;

}
else
{
/* Adding as last node*/
pTemp = pHead;
while(pTemp->next!=pHead)
pTemp = pTemp->next;
pTemp->next = pNew;
pNew->next = pHead;
printf(“Node inserted\n”);
}
return;
}

/* ADD A NEW NODE AFTER A SPECIFIED VALUE IN THE LIST */


insert_after(int val, int key)
{
struct node *pNew, *pPre, *pTemp;
// Allocate memory for the new node
pNew = (struct node *)malloc(sizeof(struct node));
pNew->data = val;

if(pHead == NULL) /*Adding to empty list*/


{
pHead = pNew;
pHead->next= pNew;
}
else
{
pTemp = pHead; /* Searching insertion point*/
do
{
if(pTemp->data == key)
{ pNew->next = pTemp->next;
pTemp->next = pNew;
printf("node inserted");
return;
}
else
{
pTemp = pTemp->next;
}
} while(pTemp!=pHead);

if( pTemp==pHead)
printf(" The insertion point can’t be found\n”);
}
return;
}

/* THIS FUNCTION DISPLAYS THE CONTENTS OF THE LINKED LIST */


display( )
{
struct node *pTemp;
pTemp=pHead;
if(pTemp ==NULL)
{
printf("NO ELEMENT IN THE LIST :");
return;
}
else /* traverse the entire linked list */
do
{
printf("%d \n", pTemp ->data);
pTemp = pTemp ->next;
} while(pTemp!=pHead);
return;
}

//THIS FUNCTION COUNTS THE NUMBER OF ELEMENTS IN THE LIST


int count()
{
struct node *pTemp;
int c=1;
pTemp=pHead;
if (pHead ==NULL)
return 0;
while(pTemp->next!= pHead)
{
pTemp = pTemp ->next;
c++;
}
return(c);
}

/*THIS FUNCTION DELETES A NODE */


delete(int key)
{
struct node *pNew, *pPre, *pTemp;
if (pHead == NULL) /*DELETION in empty list*/
{
printf(" Empty linked list \n”);
}
else
{
pTemp = pHead; /* Searching DELETION point*/
do
{
if(pTemp->data == key)
{
if(pTemp==pHead && pTemp->next==pHead)
{
free(pTemp); /* deleting only node existing in the link
pHead=NULL;
printf(“node deleted \n");
return;
}
else if(pTemp==pHead && pTemp->next!=pHead)
{
while(pTemp->next != pHead) /*delete head node
pTemp = pTemp->next;
pTemp->next = pHead->next;
free(pHead);
pHead = pTemp->next;
printf("head node deleted \n");
return;
}
else
{
pPre->next = pTemp->next;
free(pTemp);
printf("node deleted \n");
return;
}

}
else
{
pPre = pTemp;
pTemp = pTemp->next;
}
} while(pTemp!=pHead);

if( pTemp==pHead)
printf(" The deletion point can’t be found\n");
}
return;
}
Application of Circular Linked List:
Josephus' Problem:
This algorithm is named for a historian of the first century, Flavius Josephus, who survived the Jewish-
Roman war due to his mathematical talents. Legend has it that he was one out of 41 Jewish rebels trapped
by the Romans. His companions preferred suicide to escape, so they decided to form a cycle and to kill every
third person and to proceed around the circle until no one was left. Josephus wasn't excited by the idea of
killing himself, so he calculated where he has to stand to survive the vicious circle.
Algorithm:
There are n people standing in a circle waiting to be executed. After the first man is executed, k−1 people
are skipped and the k-th man is executed. Then again, k−1 people are skipped and the k-th man is executed.
The elimination proceeds around the circle (which is becoming smaller and smaller as the executed people
are removed), until only the last man remains, who is given freedom. In Euclidean geometry, a circle is the
set of all points in a plane at a fixed distance, called the radius, from a fixed point, called the centre. ...

The task is to choose the place in the initial circle so that you survive (remain the last one), given n and k.

For skip value k = 4, n=8

1 2 1 2 1 2
8 8
3 3 3
7 7 7
4
6 6 6
5 5 5

Delete(4) delete(8)

1 2 1

3 3 3
7 7 7

6 6 6

Delete(5) Delete(2) delete(1)

6 6

Delete(3) delete(7), survived = 6


Program to implement Josophus Problem:
#include <stdio.h>
#include<stdlib.h>
#define NULL 0
struct node
{
int soilder;
struct node *next;
};
struct node *head, *current;
int tot_soilders;
main()
{
int ch,n;
head = NULL;
while(1)
{
printf("\n1. soilder list creation");
printf("\n2. Display soilder list");
printf("\n3. Sucide");
printf("\n0. Exit");
scanf("%d",&ch);

switch(ch)
{
case 1:
printf("\nEnter the total no. of soilders");
scanf("%d",&n);
create_list(n);
break;
case 2:
display();
getch();
break;
case 3:
if (tot_soilders <= 1)
printf("There Should Be Atleast 2 Soilders in the
List");
else
{
printf("\nEnter the no by which sucide is to be
commited");
scanf("%d",&n);
if ( n < 1 )
printf("\nInvalid Number!");
else
printf("\nThe only Soilder left after
sucide session is %d ",left_after_sucide(n));
}
getch();
break;
case 0:
return;
default :
printf("\nINVALID CHOICE");
getch();
}
}
}

create_list(int data)
{
struct node *last,*New;
int i;
head=NULL;
for(i=1;i<=data;i++)
{
New=(struct node *)malloc(sizeof(struct node));
New->soilder=i;
New->next=NULL;
tot_soilders=tot_soilders+1;
if(head==NULL)
{
head=New;
last=New;
New->next=head;
}
else
{
New->next=last->next;
last->next=New;
last = New;
}
}
}

display()
{
if (head == NULL)
{
printf("\nNo Soilders in the Queue");
return;
}
printf("%d",head->soilder);
printf("%c ",2);
current = head->next;
while( current != head)
{
printf("%d ",current->soilder);
current = current->next;
}
return;
}
int left_after_sucide(int by_n)
{
int i=1,j,dead_sol;
struct node *save;
current = head;

for(i=1; i<tot_soilders; i++)


{
for (j=1;j< by_n;j++)
{
save = current;
current = current->next;
}
save->next = current->next;
if (current == head)
{
head = current->next;
}
dead_sol = current->soilder;
free(current);
display();
printf("\n\n%d%c is Dead \n",dead_sol,1);
current = save->next;
}
head = current;
display();
tot_soilders = 1;
return(head->soilder);
}
Doubly Linked Lists

Doubly Linked List (DLL) is a type of Linked List in which each data item points to the
next and also to the previous data item. This "linking" is accomplished by keeping two
address variables (pointers) together with each data item. These pointers are used to store the
address of the previous and the address of the next data items in the list.

The structure that is used to store one element of a linked list is called a node like in Linked
Lists.

A node has three parts: data, previous address and next address.

The data part contains the necessary information about the items of the list, the previous
address part contains the address of the previous node, the next address part contains the
address of the next node.

Basic double linked list fragment:

#include<stdio.h>
#include<conio.h>
#include<alloc.h>

struct node
{
int no;
struct node *pre,*next;
};
struct node *head=NULL,*tail=NULL;

void main()
{
int ch;
clrscr();
do
{
printf("\n\n\n 1 Append");
printf("\n 2 Forward Traverse");
printf("\n 3 Insert after the given number");
printf("\n 4 Insert before the given number");
printf("\n 5 Insert By Position ");
printf("\n 6 Delete By Value ");
printf("\n 7 Delete by Position");

printf("\n 0 EXIT");
printf("\n Enter your choice");
scanf("%d",&ch);
switch(ch)
{
case 1:
Append();
break;
case 2:
ftraverse();
break;
case 3:
insertafter();
break;
case 4:
insertbefore();
break;
case 5:
insertbypos();
break;
case 6:
delByValue();
break;
case 7:
delByPos();
break;
case 0:
break;
default:
printf("\n Invalid Choice");
}
}while(ch!=0);
getch();
}

// Appending a new node


void Append()
{

struct node *pNew;


pNew =(struct node*)malloc(sizeof(struct node));
printf("\nEnter no");
scanf("%d",& pNew ->no);
pNew ->next=NULL;
if(head==NULL)
{
head= pNew;
tail= pNew;
head->pre=NULL;
return;
}
tail->next= pNew;
pNew ->pre=tail;
tail= pNew;
}

//Displaying the contents of the list


void ftraverse()
{
struct node *p=head;
if(head==NULL)
{
printf("\n Empty Link List");
return;
}
while(p!=NULL)
{
printf(" %d",p->no);
p=p->next;
}
}

// Inserting a node after a specified number in the node


// Insert by number
void insertafter()
{
int val;
struct node *p =head,* pNew;
if(head==NULL)
{
printf("\nEmpty LINK lIST");
return;
}

printf("\n Enter number after which you want to INSERT");


scanf("%d",&val);
if(val==tail->no)
{
pNew =(struct node*)malloc(sizeof(struct node));
printf("\nENTER number");
scanf("%d",& pNew ->no);
tail->next= pNew;
pNew ->pre=tail;
tail= pNew;
tail->next=NULL;
printf("\n NODE INSERTED");
return;
}
while(p->next!=NULL)
{
if(val==p->no)
{
pNew =(struct node*)malloc(sizeof(struct node));
printf("\nEnter number");
scanf("%d",& pNew ->no);
pNew ->next=p->next;
pNew ->pre=p;
p->next= pNew;
pNew ->next->pre= pNew;

printf("\n Node Inserted");


return;
}
p=p->next;
}
printf("\n%d Number Not found",val);
return;
}

// Insert a node before a specified number


void insertbefore()
{
int val;
struct node *p =head,* pNew;
if(head==NULL)
{
printf("\nEmpty LINK lIST");
return;
}

printf("\n Enter number BEFORE which you want to INSERT");


scanf("%d",&val);
if(val==head->no)
{
pNew =(struct node*)malloc(sizeof(struct node));
printf("\nENTER number");
scanf("%d",& pNew ->no);
head->pre= pNew;
pNew ->next=head;
head= pNew;
head->pre=NULL;
printf("\n NODE INSErted");
return;
}
while(p!=NULL)
{
if(val==p->no)
{
pNew =(struct node*)malloc(sizeof(struct node));
printf("\nENTER number");
scanf("%d",& pNew ->no);
pNew ->pre=p->pre;
pNew ->next=p;
pNew ->pre= pNew;
pNew ->pre->next= pNew;
printf("\n Node inserted");
return;
}
p=p->next;
}
printf("\n%d Number not found",val);
return;
}

// Insert a new node after a specified position in the list

void insertbypos()
{
int val;
struct node *p =head,* pNew;
int non=0,i,pos;
if(head==NULL)
{
printf("\nEmpty LINK lIST");
return;
}

printf("\nEnter the position");


scanf("%d",&pos);
while(p!=NULL)
{
non++;
p=p->next;
}

if (pos<1&&pos>non+1)
{
printf("\n Invalid Position");
return;
}

if(pos==1)
{
pNew =(struct node*)malloc(sizeof(struct node));
printf("\nENTER number");
scanf("%d",& pNew ->no);
head->pre= pNew;
pNew ->next=head;
head= pNew;
head->pre=NULL;
printf("\n Node inserted");
return;
}

if(pos==non+1)
{
pNew =(struct node*)malloc(sizeof(struct node));
printf("\nEnter number");
scanf("%d",& pNew ->no);
tail->next=n;
pNew ->pre=tail;
tail= pNew;
tail->next=NULL;
printf("\n Node inserted");
return;
}
p=head;
for(i=1;i<pos-1;i++)
{
p=p->next;
}
pNew =(struct node*)malloc(sizeof(struct node));
printf("\nENTER number");
scanf("%d",& pNew ->no);
pNew ->next=p->next;
pNew ->pre=p;
p->next= pNew;
pNew ->next->pre= pNew;
printf("\n NODE Inserted");
return;
}

// Delete a node with specified number in the node


void delByValue()
{
int val;
struct node *p =head;
int i,pos;
if(head==NULL)
{
printf("\nEmpty LINK lIST");
return;
}

printf("\nEnter the number to be deleted");


scanf("%d",&val);
if(head==tail&&val==head->no)
{
free(p);
head=tail=NULL;
printf("\nNode Deleted");
return;
}
else if (val==head->no)
{
head=head->next;
head->pre=NULL;
free(p);
printf("\nNode Deleted");
return;
}
else if(val==tail->no)
{
p=tail;
tail=tail->pre;
tail->next=NULL;
free(p);
printf("\nNode Deleted");
return;

}
while(p->next!=NULL)
{
if(val==p->no)
{
p->pre->next=p->next;
p->next->pre=p->pre;

free(p);
printf("\nNode Deleted");
}
p=p->next;
}
printf("\n Node not Found") ;
return;
}

// Delete a node by position


void delByPos()
{
struct node *p =head;
int non=0,i,pos;
if(head==NULL)
{
printf("\nEmpty LINK lIST");
return;
}

printf("\nEnter the POSITION which is to be deleted");


scanf("%d",&pos);
while(p!=NULL)
{
non++;
p=p->next;
}
p=head;
if(pos<1||pos>non);
{
printf("\n INvalid Position");
}

if(head==tail&&pos==1)
{
free(p);
head=tail=NULL;
printf("\nNODE Deleted");
return;
}
else if (pos==1)
{
head=head->next;
head->pre=NULL;
free(p);
printf("\nNode DELeted");
return;
}
else if(pos==non)
{
p=tail;
tail=tail->pre;
tail->next=NULL;
free(p);
printf("\nNode DELeted");
return;

}
for(i=0;i<pos-1;i++)
{
p=p->next;
}
p->pre->next=p->next;
p->next->pre=p->pre;

free(p);
printf("\nNode Deleted");
return;
}
Application :
 Palindrome checking using doubly linked list

Linked List problems:


1. Implement stack using linked list
2. Implement queue using linked list

You might also like