Upload
others
View
2
Download
0
Embed Size (px)
Citation preview
UNIT II –LINEAR DATA STRUCTURES
CHAPTER 4 – LINKED LIST
4.1 Introduction to Abstract Data Types:
An Abstract Data type (ADT) is a set of operations that can be viewed as an extension of modular design. Objects like lists, sets and graphs, along with their operation, can be viewed as abstract data types, just as integers, reals and Booleans are data types. The basic idea is that implementation of these operations is written once in the program, and any other part of the program that needs to perform an operation on the ADT can do so by calling the appropriate function. Examples are,
List ADT Stack ADT Queue ADT, …..
4.2 List:
A list is a sequence of zero or more elements of a given type. The list is represented as sequence of elements separated by comma.
A1, A2, A3,…., AN
Where, N > 0 and Ai is of type element.
4.2.1 List as an ADT:
While considering the list as an Abstract Data type, must specify the items and operations of the list. The list can grow or shrink. The list can grow or shrink. The element in a list is represented by “last”.
4.2.2 Operations of list:
The various operations that can be performed on a list are as follows:
Insertion Deletion Locate Retrieve Displaying list
4.2.2.1 Insert operation:
Inserting an item in the list involves traversing till the position, ‘p’ where item, ‘x’ is to be inserted and all the items starting from the position ‘p’ is moved one position down the list and the item, ‘x’ inserted at position, ‘p’
1
Consider the list element shown below,
…
The item, x to be inserted is 40 and the position, p = 3.
Then, the item, x = 40 is inserted at the position, p = 3
4.2.2.2 Deletion operation:
Deleting an item, x from the list involves traversing the list till the position, p. Delete the item in the position, p and moving items next to the deleted item, one position ahead. Consider the elements shown below.
Here, the position, p = 2 and the item, ‘x’ to be deleted = 30Delete the item in the position, p = 2
2
5
last
Position of item
10 20 30 50 60
0 1 2 3 4
last
10 20 30 40 50
0 1 2 3 4
60
last
10 20 30 50
0 1 2 3 4
60
5
last
10 20 30 40 50
0 1 2 3 4
60
5
last
10 20 40 50
0 1 2 3 4
60
All items starting from the position, p is moved one position ahead.
Hence, the item, x = 30 is deleted from the list
4.2.2.3 Location operation:
Locating the position of the given element, if it is present in the list is location operation. Consider the list shown below,
Here, the position of an item, 30 it to be located. Traverse the list, to find the position of an item, 30. The item, 30 is present in the list its position is returned as 2. Consider the list shown below,
Here, the position of an item, 70 is to be located. The item, 70 is not present in the list. So, it cannot be located.
4.2.2.4 Retrieve operation:
For a given position and a given list, the element has to be retrieved corresponding to the position. Consider the following list,
3
last
10 20 40 50 60
0 1 2 3 4
last
10 20 30 40 50
0 1 2 3 4
60
last
10 20 30 40 50
0 1 2 3 4
60
last
10 20 30 40 50
0 1 2 3 4
60
The entire list is checked for the given position. If the position is not present, display “position does not exist”. Otherwise, the element in that position is printed. Here, the retrieved element is 30.
4.2.2.5 Print list operation:
Printing all items or elements in the list. Consider the list show below
The element starting from the first position of the list to the last position of list is printed as 10, 20, 30, 40, 50, and 60
4.3 Implementation of list:
The list can be implemented in the following ways:
1. Array implementation 2. Linked – list implementation3. Cursor implementation.
4.4 Array Implementation of list: All of the above operations can be implemented by using an array. Even if the array is dynamically allocated, an estimate of the maximum single of the list is required.
Figure 4.1 Insertion in Array based List
4
last
10 20 30 40 50
0 1 2 3 4
60
4.4.1 Source code for Array Implementation of list:
/*Array Implementation of list:*/#include<stdio.h>#include<conio.h>#define max 100struct list{ int a[max]; int last; }S; void main(){ int x,p,loc,c; clrscr() ; void insert(int,int); int locate(int); void delete(int); clrscr(); while(1) { printf("1.insert 2.locate 3.delete 4.exit\n"); scanf("%d",&c); switch(c) { case 1:
printf("enter the element & its position\n"); scanf("%d %d",&x,&p); insert(x,p); break;
case 2: printf("enter element to b located\n"); scanf("%d",&x); loc=locate(x); if(loc==0) printf("element not found"); else printf("location of x=%d\n",loc);
5
Note: Simple arrays are generally not used to implement lists, because the running
time for insertions and deletions is so slow and the list size must be known in advance
break; case 3:
printf("enter position to delete element\n"); scanf("%d",&p); delete(p); break;
case 4: exit(0);
} }
} void insert(int x,int p) { int q; if(S.last>=max) { printf("list full"); } else if((p>S.last+1)||(p<1)) printf("pos doesnot exist"); else { for( q=S.last;q>=p;q--) S.a[q+1]=S.a[q]; S.last=S.last+1; S.a[p]=x; } } int locate(int x) { int q; for(q=1;q<=S.last;q++) { if(S.a[q]==x) return q; } return(0); }
void delete(int p) { int q; if((p>S.last)||(p<1)) { printf("position does not exist");
6
} else { S.last=S.last-1; for(q=p;q<=S.last;q++) S.a[q]=S.a[q+1]; } }
SAMPLE INPUT & OUTPUT:
/*Array Implementation of list:*/Array Implementation of List1.insert 2.locate 3.delete 4.exit1enter the element & its position21Array Implementation of List1.insert 2.locate 3.delete 4.exit
1enter the element & its position32Array Implementation of List1.insert 2.locate 3.delete 4.exit2enter element to b located3location of x=2Array Implementation of List1.insert 2.locate 3.delete 4.exit3enter position to delete element1Array Implementation of List1.insert 2.locate 3.delete 4.exit2enter element to b located2element not foundArray Implementation of List1.insert 2.locate 3.delete 4.exit4
7
4.5 Linked lists Implementation: In order to avoid the linear cost of insertion and deletion, we need to ensure that the list is not stored contiguously, since otherwise entire parts of the list will need to be moved. The general idea of linked lists is as follows:
The linked list consists of a series of structures /nodes Each the contains two fields: Data (element) Next (address of the next node) The last cell’s next pointer points to NULL.
There are three types of the linked lists, which are as follows.
i) Singly Linked Listii) Doubly Linked Listiii) Circularly Linked List
4.5.1 Singly Linked Lists:
The representation of a singly linked list is shown below:
Figure 4.2 Singly Linked List
Each node contains two fields. The first field contains the data and second contains the address of the next node.
8
Node
NextData
NULL
Head
Node
Note: Head will always contain one field, i.e., the address of the first Last node’s next field is NULL, to indicate the end of the list
Figure 4.3 Example for Singly Linked List
4.5.1.1 Operations of Singly linked list: We have to specify to specify the operations that can be performed on a singly linked list. The operations that can be performed on a singly linked list are given below.
Insertion operationi) Insertion at beginning.ii) Insertion at given position.iii) Insertion at end.
Deletion operationi) Deletion at beginning.ii) Deletion at given position.iii) Deletion at end.
4.5.1.2 Insert operation in singly linked list:
Inserting an element into a linked list insertion in a singly linked list falls under three categories and they are as follows,
a) Insertion at beginning b) Insertion at given positionc) Insertion at end
Insertion at beginning: For example, Consider the singly linked list shown below:
Figure 4.4 Singly Linked List for inserting first
9
Head
1000
10 2000
1000
20 3000 30 NULL
2000 3000
Head
1000
10 2000
1000
20 3000 30 NULL
2000 3000
Suppose, we want to add a new node whose address is 1000 at the beginning of the list. The steps given below are to be followed.
Step1: First create a new node. Assume the address to be 500 and data to be placed is5Step2: Assign the data, to the data field of the new node.
Step 3: assign the address of the head to the “next field” of the new node.
Step 4: assign the address of the new node to the address of the head.
Step 5: Once the address of the new node is assigned to the address of the head, the existing head address is replaced with the new node’s address.
Insertion at the Given Position:
Suppose, we want to add a new note at the given position in the list, we must specify the position of the list the node has to be inserted. For inserting the node at the given position the list, the steps given below are to be followed.For example, Consider the singly linked list shown below, and insert the element 25 at position, 3.
10
500
5
Head
1000
10 2000
1000
20 3000 30 NULL
2000 3000
500
5 1000
Head
1000
10 2000
1000
20 3000 30 NULL
2000 3000
1000 2000 3000500
5 1000 10 2000 20 3000 30 NULL
Head500
Figure 4.5 Singly Linked List for inserting 25 at position 3
Step1: Create a new node. Assign the data that is read to the data field of the new node.
Step 2: Traverse the list up to the position 2(3-1). The result of traversing up to the position 2.
Step 3: The next field valve of the node at position, 2 is assigned the address of new node.
11
Head
1000
10 2000
1000
20 3000 30 NULL
2000 3000
2500
Head
1000
10 2000
1000
20 3000 30 NULL
2000 3000
25
Head
1000
10 2000
1000
20 3000 30 NULL
2000 3000
2500
25 2000
Head
1000
10 2000
1000
20 3000 30 NULL
2000 3000
2500
25 3000
Step 4: The next field valve of the node at position, 2 is replaces with the new node’s address
Insertion at the end:
Suppose, we want to insert an element of the end of the list we have to follow the steps give below. Consider the singly linked list shown below,
Figure 4.6 Singly Linked List for inserting 40 at end
Step 1: Create a new node and place the data in the data field of new node.
Step 2: Traverse the list, until the last node is reached.
12
Head
1000
10 2000
1000
20 2500 30 NULL
2000 3000
2500
25 3000
Head
1000
10 2000
1000
20 3000 30 NULL
2000 3000
4000
40
Head
1000
10 2000
1000
20 3000 30 NULL
2000 3000
Step 3: Next field of the last node is assigned the address of the new node
Step 4: new node’s next field is assigned NULL. Since, it is a last node in the list.
4.5.1.3 Delete Operations in singly linked list:
Deleting an element from the list. Deletion in a singly linked list falls under three categories
iv) Deletion at beginning.v) Deletion at given position.vi) Deletion at end.
13
4000
40
Head
1000
10 2000
1000
20 3000 30 NULL
2000 3000
4000
40
Head
1000
10 2000
1000
20 3000 30 4000
2000 3000
4000
40 NULL
Head
1000
10 2000
1000
20 3000 30 4000
2000 3000
Deletion at Beginning: Deleting a node at the first position involves the following steps. Consider the singly linked list shown below,
Figure 4.7 Singly Linked List for Deleting at first
Step 1: Assign the first nodes a next field value to the head node.
Step 2: Delete the node at the beginning
Deletion at the given position:
For deleting the node at the given position in the list, the steps given below are to be followed. Consider the singly linked list shown below, and delete the node at position 2
Figure 4.8 Singly Linked List for Deleting node at position 2
14
Head
1000
10 2000
1000
20 3000 30 NULL
2000 3000
Head
1000
2000
20 3000 30 NULL
2000 3000
10 2000
Head 2000
20 3000 30 NULL
2000 3000
Head
1000
10 2000
1000
20 3000 30 NULL
2000 3000
Step 1: Create two dummy pointers. One dummy pointer contains the same address as the head.
Step 2: Traverse the list using the dummy pointer p1 till it reaches the previous node of the node to be deleted and assign the next field of p1 to p2.
Step3: Assign the address of p2’s next field to p1 next field. By assigning 3000 to p1’s next field automatically a link will be made as shown below:
Step 4: Delete both p1 and p2
15
Head
1000
10 2000
1000
20 3000 30 NULL
2000 3000
p11000
p2Head
1000
10 2000
1000
20 3000 30 NULL
2000 3000
p11000 2000
p2Head
1000
10 3000
1000
20 3000 30 NULL
2000 3000
p11000 2000
Head
30001000
10 2000
1000
30 NULL
Deletion at the end:
Suppose, we want to delete an element at the end of the list we have to follow the steps given below. Consider the singly linked list shown below:
Figure 4.9 Singly Linked List for Deleting at end.
Step 1: Create two pointers p1 and p2 and assign the address of head to p1.
Step 2: Traverse the list using p1 until it reaches the previous node of the last node in the list.
Step 3: Assign the next field of p1 to p2
16
Head
1000
10 2000
1000
20 3000 30 NULL
2000 3000
Head
1000
10 2000
1000
20 3000 30 NULL
2000 3000
p11000
Head
1000
10 2000
1000
20 3000 30 NULL
2000 3000
p12000
Head
1000
10 2000
1000
20 3000 30 NULL
2000 3000
p12000 p23000
Step 4: make the next field of p1 to NULL
Step 5: Delete p1 and p2
4.5.1.4 Routines for Singly Linked list:
typedef int ElementType; #ifndef _List_H #define _List_H struct Node; typedef struct Node *PtrToNode; typedef PtrToNode List; typedef PtrToNode Position; List MakeEmpty( List L ); int IsEmpty( List L ); int IsLast( Position P, List L ); Position Find( ElementType X, List L ); void Delete( ElementType X, List L ); Position FindPrevious( ElementType X, List L ); void Insert( ElementType X, List L, Position P ); void DeleteList( List L ); Position Header( List L ); Position First( List L ); Position Advance( Position P ); ElementType Retrieve( Position P );
#endif /* END */
17
Head
1000
10 2000
1000
20 NULL 30 NULL
2000 3000
p12000 p23000
Head
1000
10 2000
1000
20 NULL
2000
struct Node { ElementType Element; Position Next; };
List MakeEmpty( List L ) { if( L != NULL ) DeleteList( L ); L = malloc( sizeof( struct Node ) ); if( L == NULL ) FatalError( "Out of memory!" ); L->Next = NULL; return L; }
int IsEmpty( List L ) { return L->Next == NULL; }
int IsLast( Position P, List L ) { return P->Next == NULL; }
Position Find( ElementType X, List L ) { Position P;
/* 1*/ P = L->Next;/* 2*/ while( P != NULL && P->Element != X )/* 3*/ P = P->Next;
/* 4*/ return P; }
void Delete( ElementType X, List L ) { Position P, TmpCell; P = FindPrevious( X, L ); if( !IsLast( P, L ) ) /* Assumption of header use */ { /* X is found; delete it */
18
TmpCell = P->Next; P->Next = TmpCell->Next; /* Bypass deleted cell */ free( TmpCell ); } }
Position FindPrevious( ElementType X, List L ) { Position P;/* 1*/ P = L;/* 2*/ while( P->Next != NULL && P->Next->Element != X )/* 3*/ P = P->Next;/* 4*/ return P; }
void Insert( ElementType X, List L, Position P ) { Position TmpCell;/* 1*/ TmpCell = malloc( sizeof( struct Node ) );/* 2*/ if( TmpCell == NULL )/* 3*/ FatalError( "Out of space!!!" );/* 4*/ TmpCell->Element = X;/* 5*/ TmpCell->Next = P->Next;/* 6*/ P->Next = TmpCell; }
void DeleteList( List L ) { Position P, Tmp;/* 1*/ P = L->Next; /* Header assumed *//* 2*/ L->Next = NULL;/* 3*/ while( P != NULL ) {/* 4*/ Tmp = P->Next;/* 5*/ free( P );/* 6*/ P = Tmp; } }
Position Header( List L ) { return L; }
Position First( List L ) {
19
return L->Next; } Position Advance( Position P ) { return P->Next; } ElementType Retrieve( Position P ) { return P->Element; }
4.5.1.5 Source code for Singly Linked list:
/*Singly Linked List */#include<stdio.h>#include<conio.h>#include<stdlib.h>int i;struct node{ int data; struct node *next;}*head,*temp,*temp1;void main(){ int ch; void create(); void display(); void delete(); void mnull(); void insert(); void locate(); clrscr(); head=(struct node *)malloc(sizeof(struct node)); head->next=NULL; while(1) { printf("\n1.create 2.display 3.make null 4.delete 5.insert 6.locate 7.exit\n"); printf(“\nEnter the choice:\n”); scanf("%d",&ch); switch(ch) { case 1:
create(); break;
case 2:
20
display(); break;
case 3: mnull(); break;
case 4: delete(); break;
case 5: insert(); break;
case 6: locate(); break;
case 7: exit(0);
} } getch(); } void create() { printf("\nenter element"); if(head->next==NULL) { temp=(struct node *)malloc(sizeof(struct node)); scanf("%d",&temp->data); head->next=temp; temp->next=NULL; } else {
temp1=(struct node *)malloc(sizeof(struct node));scanf("%d",&temp1->data);temp->next=temp1;temp1->next=NULL;temp=temp1;
} } void display() { temp=head; if((temp->next)==NULL) { printf("\nlist empty\n"); }
21
else { printf("\t\t\n\nelements in list\t\n\n"); while(temp->next!=NULL) { printf("-->%d",temp->next->data); temp=temp->next; } } } void mnull() { temp=head; temp->next=NULL;
} void delete() { int p; temp=head; printf("enter position to be deleted"); scanf("%d",&p); for(i=1;i<p;i++) temp=temp->next; temp->next=temp->next->next; } void insert() { int p; int c; temp1=(struct node *)malloc(sizeof(struct node)); printf("\nto insert 1.first 2.last 3.anywhere\n"); scanf("%d",&c); printf("enter element to be inserted\n"); scanf("%d",&temp1->data); switch(c) { case 1:
temp1->next=head->next; head->next=temp1; break;
case 2: temp=head->next; while(temp->next!=NULL) temp=temp->next; temp->next=temp1;
22
temp1->next=NULL; break;
case 3: printf("enter position\n"); scanf("%d",&p); if(p==1) {temp1->next=head->next; head->next=temp1; } else { temp=head->next; for(i=1;i<p-1;i++) temp=temp->next; temp1->next=temp->next; temp->next=temp1; }
} } void locate() { int n; temp=head->next; printf("enter element to be located\n"); scanf("%d",&n); for(i=1;temp->data!=n;i++) temp=temp->next; if(temp->data==n) printf("element is at position %d\n",i); else printf("element not found\n");}SAMPLE INPUT & OUTPUT:
/*Singly Linked List */1.create 2.display 3.make null 4.delete 5.insert 6.locate 7.exitEnter the choice:1enter element 51.create 2.display 3.make null 4.delete 5.insert 6.locate 7.exitEnter the choice:1enter element61.create 2.display 3.make null 4.delete 5.insert 6.locate 7.exitEnter the choice:1enter element71.create 2.display 3.make null 4.delete 5.insert 6.locate 7.exitEnter the choice:2elements in list
23
-->5-->6-->71.create 2.display 3.make null 4.delete 5.insert 6.locate 7.exitEnter the choice:5to insert 1.first 2.last 3.anywhere3enter element to be inserted8enter position21.create 2.display 3.make null 4.delete 5.insert 6.locate 7.exitEnter the choice:2elements in list-->5-->8-->6-->71.create 2.display 3.make null 4.delete 5.insert 6.locate 7.exitEnter the choice:6enter element to be located 6element is at position 31.create 2.display 3.make null 4.delete 5.insert 6.locate 7.exitEnter the choice:4enter position to be deleted 11.create 2.display 3.make null 4.delete 5.insert 6.locate 7.exitEnter the choice:2elements in list-->8-->6-->71.create 2.display 3.make null 4.delete 5.insert 6.locate 7.exitEnter the choice:31.create 2.display 3.make null 4.delete 5.insert 6.locate 7.exitEnter the choice:2list empty1.create 2.display 3.make null 4.delete 5.insert 6.locate 7.exitEnter the choice: 7
4.5.2 Doubly linked lists:
Doubly linked list is a collection of nodes where nodes are connected by forwarded and backward link. The diagrammatic representation is shown below:
Figure 4.10 Doubly Linked List
24
Head
Each node in the doubly linked list contains 3 fields.
The first field contains the address of the previous node. The second field contains the data The third field contains the address of the next node.
The head contains the address of the first node. The strike out in the first field of the first node indicates that there is no previous node. The strike out in the last field of last node indicates that is the end of the list.
4.5.2.1 Doubly linked list as an ADT:
While considering the doubly linked list as an Abstract Data Type, we must specify the items and operations associated with doubly liked list. Since doubly linked list is a collection of nodes we must specify the things contained in a node. The representation of node in doubly linked list is shown below.
Figure 4.11 Doubly Linked List ADT 4.5.2.2 Operation in a Doubly Linked List:
1. insert 2. Delete 3. Make NULL4. Search 5. Locate 6. Print
4.5.2.3 Insertion operation in Doubly linked list : Insertion of a node in a doubly linked list falls under 3 categories,
i) insertion at beginii) insertion at Middle iii) insertion at end
Insertion at beginning:
Insertion a node at the beginning of the list involves following steps. Consider the list shown below,
25
Data
Address of the next node
Address of the previous node
Figure 4.12 Doubly Linked List for inserting at beginning
Step 1: Create a new node
Step 2: Place the data in the data field to new node
Step 3: Assign the address of the head to the next field to new node. This creates a forward link.
26
1000
N 10 2000 1000 20 3000 302000
(Assume address to be 500)
1000
N 10 2000 1000 20 3000 302000
1000
N 10 2000 1000 20 3000 302000
05 1000
(Assume data to be 5)
1000
N 10 2000 1000 20 3000 302000
5
Step 4: Assign the address of the new node to the head pointer’s previous field. This creates a backward link
Step 5: Assign the address of the new node to the head itself.
Step 6: Make the head pointer’s previous field NULL
Insertion at the Middle Consider the list shown below,
Figure 4.13 Doubly Linked List for inserting at middle
Suppose, we want to add a new node at the 2nd position, the steps to be followed are
27
1000
N 10 2000 1000 20 3000 30200005 1000
N 10 2000 1000 20 3000 30200005 1000
500
N 10 2000 1000 20 3000 30200005 1000
500
1000
N 10 2000 1000 20 3000 302000
Step 1: Create a new node
Step 2: Place the data field of new node
Step 3: Create a dummy pointer ‘p’. Assign the address of the head to the dummy pointer.
Step 4: Move the dummy pointer till the previous node position where the new node has to be inserted
28
Assume address to be 2500
1000
N 10 2000 1000 20 3000 302000
Assume data to be 25
1000
N 10 2000 1000 20 3000 302000
25
p1000
N 10 2000 1000 20 3000 302000
25
1000
p1000
N 10 2000 1000 20 3000 302000
25
1000
Step 5: Assign the address of dummy pointer’s next field to the new node next field
Step 6: Assign the new node address to address of the dummy pointer next field’s previous field to the new nodes next field.
Step 7: Assign the Address of the dummy pointer to the new node’s next field
Step 8: Assign the address of the dummy pointer to the new node’s previous field
29
p1000
N 10 2000 1000 20 3000 302000
25 2000
1000
p1000
N 10 2000 2500 20 3000 302000
25 2000
1000
p10001000
N 10 2500 2500 20 3000 302000
25 2000
Step 9: Delete the dummy pointer
Insertion at the End: Consider the list shown below,
Figure 4.14 Doubly Linked List for inserting at End
Suppose we want to add a new node at the last position, the steps to be followed are
1. Create a new node & place the data that is read
30
p10001000
N 10 2500 2500 20 3000 302000
1000 25 2000
1000
N 10 2500 2500 20 3000 302000
1000 25 2000
1000
1000 20N 10 2000
2. Create a dummy pointer. Assign the address of head to the dummy pointer
3. Move the dummy pointer to the last node in the list
4. Assign the address of the new node to the dummy pointer’s next field
31
10001000
1000 20N 10 2000
30
1000
1000 20N 10 2000
30
10001000
1000 20N 10 2000
30
20001000
1000 20 3000N 10 2000
30
5. Assign the dummy pointer address to the new node previous field
6. Make the new node’s next field NULL
7. Delete the dummy pointer
4.5.2.4 Deletion Operation in doubly Linked List:
Deletion at First: Consider the list shown below
Figure 4.15 Doubly Linked List for Deletion at first
32
1000
1000 2010 2000
20001000
1000 20 3000N 10 2000
302000
20001000
1000 20 3000N 10 2000
302000
1000
1000 20 3000N 10 2000
302000
1. Create a dummy pointer. Assign the address of the head to the dummy
2. Assign the address of next field of head to head itself.
3. Delete the dummy pointer and head pointer’s previous field is made NULL.
Deletion at Middle: Consider the list shown below
Figure 4.15 Doubly Linked List for Deletion at Middle
1. Create two dummy pointers. Assign the address of head to one dummy pointer. Let it be p1
dp1
33
20
2000
1000
10 2000 1000 20 3000 302000
p10001000
1000 2010 2000
p10001000
1000 2010 2000
p1 p2
1000 3000
1000
10 2000 20 302000
1000
403000
2. Traverse the list using dummy pointer d1 till the previous node of the node to be deleted, is reached.
3. Assign the dummy pointer p1’s next field address to the p2
4. Assign the address of dummy pointer p2’s next field to p1’s next field
5. Assign the address of dummy pointer p1 to p2 next field’s previous field
34
p1 p2
1000 3000
1000
10 2000 20 302000
2000
403000
p1 p21000
N 10 2000 1000 20 3000 4000302000
2000
403000
3000
p1 p21000
N 10 2000 1000 20 4000 4000302000
2000
403000
3000
p1 p21000
N 10 2000 1000 20 4000 4000302000
2000
402000
3000
6. Delete the pointers p1 & p2
Deletion at End:
Consider the list shown below
Figure 4.16 Doubly Linked List for Deletion at End
1. Create 2 dummy pointers. Assign the Address of the head to the dummy pointer. Let it be p 1
2. Move the list using p1 till the previous node of the node to be deleted
2
3. Assign the address of p1’s next field to p2
35
1000
N 10 2000 1000 20 4000 N302000
1000
N 10 2000 1000 20 4000 N302000
p2p1
1000 3000
1000
N 10 2000 20 N302000
1000
p2p1
1000 3000
1000
N 10 2000 20 N302000
2000
4. Make p1’s next field NULL. Delete both p1 & p2
4.5.2.5 Routines for Doubly Linked List:
Struct type nodevar : int data;struct type node *next,*prev;struct node *head,*temp,*temp1,*temp2,*t;
Procedure initializebegin head : = new node;head->next:=NULL;End; // procedure initialize
Procedure createbegin if(headnext==NULL)then temp:=new node; Enter the element to create Get the value of tempdata; Headnext:=temp; Tempnext:=NULL; Tempprev:=NULL; else if(tempnext==NULL) then
temp1:=new node;
36
p1
1000 3000
1000
N 10 2000 20 N302000
2000 p23000
1000
N 10 2000 1000 20
Get the value of temp1data; Tempnext:=temp1; temp1next:=NULL; temp1prev:=temp; temp:=temp1;end;//ifend;//outer if
End; procedure create
Procedure Delete begin
temp:=head; Enter the position to be deleted
Get the position value as m;For j= 1 to m do begintemp:=tempnext;tempnext:=tempnextnext;tempnextprev:=temp;
end;//forend;//procedure delete
Procedure insert begin
temp:=head; temp1:=new node;Get the position value as m; Get the value of temp1data; For i=1 to mDobegin Temp:=tempnext; temp1next:=tempnext; temp1prev:=temp; tempnext:=temp1; end;//for
end;//procedure insert
procedure Searchbegin
var: int dat; temp:=head; give the data to be searched;for j = 0 to tempnext !=NULL do
37
begin temp:=tempnext; if(tempdata==data) then display the data position as value jend;//for
end;//procedure search Procedure displaybegin temp:=head; while(temp->next!=NULL) do
begin display tempnextdata value; temp:=tempnext;
end;//whileend;// procedure display
4.5.2.6 Source Code for Doubly Linked List:
/* Doubly Linked List */#include<stdio.h>#include<conio.h>#include<malloc.h>#include<process.h>
struct node{ int data; struct node *next,*prev;}*head,*cur,*t,*q;
void create();void add();void insert();void del();void delpos();void disp();void create(){ head=(struct node *) malloc(sizeof(struct node)); head->next=NULL; head->prev=NULL;}void add(){
38
cur=head; while(cur->next!=NULL)
cur=cur->next; t=(struct node *) malloc(sizeof(struct node)); printf("Enter data\t"); scanf("%d",&t->data); cur->next=t; t->next=NULL; t->prev=cur;}void insert(){
int p,i;printf("Enter the position ");scanf("%d",&p);cur=head;for(i=1;i<p;i++)
cur=cur->next;t=(struct node *) malloc(sizeof(struct node));printf("Enter data\t");scanf("%d",&t->data);q=cur->next;t->next=q;q->prev=t;cur->next=t;t->prev=cur;
}void del(){
int d;printf("Enter data to delete");scanf("%d",&d);cur=head;while(cur->next!=NULL){ if(cur->next->data==d)
{ t=cur->next; cur->next=cur->next->next; cur->next->prev=cur; printf("Deleted\n"); free(t); return;}else
cur=cur->next;} printf("No such data\n");
}
39
void delpos(){
int p,i;printf("Enter the position");scanf("%d",&p);cur=head;for(i=1;i<p;i++)
cur=cur->next;t=cur->next;cur->next=cur->next->next; cur->next->prev=cur;free(t);printf("Deleted\n");
}void disp(){
cur=head;if(head->next==NULL){
printf("List is empty\n");return;
}while(cur->next!=NULL){
printf("%d<==>",cur->next->data);cur=cur->next;
}}void main(){
int ch;clrscr();create();do{
printf("\n\n1.Add\n2.Insert\n3.Delete\n4.Delete by pos\n5.Display\n6.Exit\n\n");
printf("Enter ur choice\t");scanf("%d",&ch);switch(ch){
case 1:add();break;
case 2:insert();
40
break;case 3:
del();break;
case 4:delpos();break;
case 5:disp();break;
case 6:exit(0);break;
}}while(ch<=5);getch();
}
Output of Doubly Linked list:
/* Doubly linked list*/1.Add2.Insert3.Delete4.Delete by pos5.Display6.ExitEnter ur choice 1Enter data 21.Add2.Insert3.Delete4.Delete by pos5.Display6.ExitEnter ur choice 1Enter data 31.Add2.Insert3.Delete4.Delete by pos5.Display6.ExitEnter ur choice 1Enter data 41.Add
41
2.Insert3.Delete4.Delete by pos5.Display6.ExitEnter ur choice 52<==>3<==>4<==>1.Add2.Insert3.Delete4.Delete by pos5.Display6.ExitEnter ur choice 2Enter the position 2Enter data 61.Add2.Insert3.Delete4.Delete by pos5.Display6.ExitEnter ur choice 52<==>6<==>3<==>4<==>1.Add2.Insert3.Delete4.Delete by pos5.Display6.ExitEnter ur choice3Enter data to delete 3Deleted1.Add2.Insert3.Delete4.Delete by pos5.Display6.ExitEnter ur choice 52<==>6<==>4<==>1.Add2.Insert3.Delete4.Delete by pos
42
5.Display6.ExitEnter ur choice 4Enter the position 2Deleted1.Add2.Insert3.Delete4.Delete by pos5.Display6.ExitEnter ur choice 52<==>4<==>
4.5.3 Circularly Linked List:
The circularly linked list can be implemented by making conventional change in the singly linked list (or) doubly linked list.
4.5.3.1 Implementing Circular linked list from Singly linked list:
In a Singly linked list, all nodes are connected with forward links to the next nodes in the list. The last node has a next field, NULL. Inorder to implement the circularly linked list from singly linked list, the last node’s next field is connected to the first node of the list as shown below:
Figure 4.17 Circularly Singly Linked List
4.5.3.2 Implementing Circular linked list from Doubly linked list:
In a doubly linked list, all nodes are connected with forward and backward links to the next and previous nodes respectively.
The first node’s previous field and last node’s next field is NULL. In order to implement the circularly linked list from doubly linked list, the
first node’s previous field is connected to the last node and last node’s next field is connected to the first node as shown below:
43
2000
1000
10 2000 20 3000 30 1000
2000 3000
Figure 4.18 Circularly Doubly Linked List
All the operations in circularly linked list is similar to the previous linked list implementations
4.5.3.3 Routines for Circularly linked list:
Struct type nodevar : int data;struct type node *next;struct node *head,*temp,*temp1;
Procedure initializebeginhead : = new node;head->next:=NULL;End;// procedure initialize
Procedure createbegin Enter the element to create Get the number of elements n Get the value of tempdata; Headnext:=temp; Tempnext:=head; For i=1 to n
temp1:=new node;Get the value of temp1data; Tempnext:=temp1; temp1next:=head;temp:=temp1;end;//for
End; procedure create
Procedure delete begin
temp:=head; Enter the position to be deleted
Get the position value as m;
44
1000
10 2000 20 3000 30 1000
2000 3000
For j= 1 to m do begintemp:=tempnext;tempnext:=tempnextnext;end;//for
end;//procedure delete
Procedure insertAtfirst begin
temp:=headnext; temp1:=new node;Get the position value as m; Get the value of temp1data; temp1next=temp; headnext=temp1;
end; procedure insertAtfirst
Procedure insertAtMiddlebegin
temp:=headnext; temp1:=new node;Get the position value as m; Get the value of temp1data;If position is 1 temp1next=temp; headnext=temp1;else
for j=1 to m-1 do begin
Temp:=tempnext; temp1next:=tempnext; tempnext:=temp1;end;//for
end;// procedure insertAtMiddle
Procedure insertAtLastbegin
temp:=headnext; temp1:=new node;Get the position value as m; Get the value of temp1data; while(temp->next!=head) do begin
45
temp:=tempnext;Tempnext:=temp1; temp1next:=head;end;// procedure insertAtLast
Procedure searchbegin
var: int dat; temp:=head; give the data to be searched;for j = 0 to tempdata !=NULL do begin temp:=tempnext; if(tempdata==data) then display the data position as value jend;//for
End;//procedure search
Procedure displaybegin temp:=head; while(temp->next!=head) do
begin display tempnextdata value; temp:=tempnext;
end;//whileEnd;// procedure display
4.5.3.4 Source Code for Circularly linked list:
/*Circular Linked list */#include<stdio.h>#include<conio.h>#include<malloc.h>#include<process.h>struct node{ int data; struct node *next;}*head,*cur,*t;void create();void add();void insert();void del();void delpos();void disp();
46
void create(){ head=(struct node *) malloc(sizeof(struct node)); head->next=head;}void add(){ cur=head; while(cur->next!=head)
cur=cur->next; t=(struct node *) malloc(sizeof(struct node)); printf("Enter data\t"); scanf("%d",&t->data); cur->next=t; t->next=head;}void insert(){
int p,i;printf("Enter the position ");scanf("%d",&p);cur=head;for(i=1;i<p;i++)
cur=cur->next;t=(struct node *) malloc(sizeof(struct node));printf("Enter data\t");scanf("%d",&t->data);t->next=cur->next;cur->next=t;
}void del(){
int d;printf("Enter data to delete");scanf("%d",&d);cur=head;while(cur->next!=head){ if(cur->next->data==d)
{ t=cur->next; cur->next=cur->next->next; printf("Deleted\n"); free(t); return;}else
cur=cur->next;
47
}printf("No such data\n");
}void delpos(){
int p,i;printf("Enter the position");scanf("%d",&p);cur=head;for(i=1;i<p;i++)
cur=cur->next;t=cur->next;cur->next=cur->next->next;free(t);printf("Deleted\n");
}void disp(){
cur=head;if(head->next==head){
printf("List is empty\n");return;
}while(cur->next!=head)
{printf("%d\t",cur->next->data);cur=cur->next;
}}void main(){
int ch;create();do{printf("\n\n1.Add\n2.Insert\n3.Delete\n4.Delete by pos\n5.Display\n6.Exit\n\
n");printf("Enter ur choice\t");scanf("%d",&ch);
switch(ch){
case 1:add();break;
case 2:
48
insert();break;
case 3:del();break;
case 4:delpos();break;
case 5:disp();break;
case 6:exit(0);break;
}}
while(ch<=5);getch();
}
Output of Circularly linked list:/*Circular linked list*/1.Add2.Insert3.Delete4.Delete by pos5.Display6.ExitEnter ur choice 1Enter data 41.Add2.Insert3.Delete4.Delete by pos5.Display6.ExitEnter ur choice 1Enter data 51.Add2.Insert3.Delete4.Delete by pos5.Display6.ExitEnter ur choice 1Enter data 7
49
1.Add2.Insert3.Delete4.Delete by pos5.Display6.ExitEnter ur choice 54 5 71.Add2.Insert3.Delete4.Delete by pos5.Display6.ExitEnter ur choice 2Enter the position 2Enter data 31.Add2.Insert3.Delete4.Delete by pos5.Display6.ExitEnter ur choice 54 3 5 71.Add2.Insert3.Delete4.Delete by pos5.Display6.ExitEnter ur choice 3Enter data to delete 4Deleted1.Add2.Insert3.Delete4.Delete by pos5.Display6.ExitEnter ur choice 53 5 71.Add2.Insert3.Delete4.Delete by pos
50
5.Display6.ExitEnter ur choice 4Enter the position of data to delete 2Deleted 1.Add2.Insert3.Delete4.Delete by pos5.Display6.ExitEnter ur choice 53 7
4.6 Cursor Implementation:
The cursor implementation of lists is used by many languages such as BASIC and FORTAN that do not support pointers. The two important features of the cursor implementation of linked lists are as follows:
1. The data are stores in a collection of structures. Each structure contains data and a index to the next structure.
2. A new structure can be obtained from the system’s global memory by a call to CursorSpace array. To do this, we will keep a list (the FreeList) of cells that are not in any list. The list will use cell 0 as a header.
The initial configuration is shown below:
In the above table,
Slot Element Next0 11 2
2 3
3 44 55 6
6 7
7 88 99 10
10 0
51
Slot Number of node in the list Element Data
Next Index of the Next Node.
So, that table represents the following list
Figure 4.19 List representation of above table
To perform insertion operation, (CursorAlloc) the first Node (after the header) is removed from the freelist and the element is inserted to this node.
To perform deletion operation, (CursorFree) the deleted node is added at the front of the free list.
For consistency, we implement our list with a header node.
Suppose the value of P = 5 and Q = 3, then P represent the list a, b, & c and Q represents the list d, e, f, & g. The table for cursor implementation is as follows:
52
Head
32
1
4 5 6
7 8 9 10
Note: The list will use cell 0 as a header A value of 0 for next is equivalent of a NULL pointer
Therefore, the list P has elements,
The list Q has elements
FreeList elements are
Slot Element Next0 -- 10
1 d 8
2 b 9
3 header 1
4 f 7
5 header 6
6 a 2
7 g 0
8 e 4
9 c 0
10 -- 0
53
P
Q
6 a 2 b 9 c 0
5 6 2 9
1 d 2 e 9 f 0
5 6 2 9
c 0
- 0 - 0
0 10
6.1 Routines for cursor implementation:
Routine for Node implementation:
struct Node{
ElementType Element;Position Next;
};
struct Node CursorSpace[SpaceSize];
Routine for CursorAlloc and CursorFree:
static Position CursorAlloc( ){
Position P;P = CursorSpace[0].Next;CursorSpace[0].Next = CursorSpace[P].Next;return P;
}
static void CursorFree (Position P){
CursorSpace[P].Next = CursorSpace[0]. Next;CursorSpace[0].Next = P;
}
Routine to check whether a list is empty or not:
/* It returns True if L is empty */
int IsEmpty (List L){
return CursorSpace(L).Next=0;}
Routine to check whether the current position is the last position in a linked list:
int IsLast(List L){
/* It returns true if P is the last position in List L */return CursorSpace[P].Next=0;
}
54
Routine to find the position of X in List L:
Position Find (ElementType X, List L){
Position P;P = CursorSpace[L].Next;while(P&&CursorSpace[P].Elemeny!=X)begin
P = CursorSpace[P].Next;return P;
}
Routine to implement the deletion operation:
void Delete (ElementType X, List L){
Position P, Temp;P = FindPrev(X, L); // to find previous position of element to be deleted if (!IsLast(P, L)) /* If X is found, then delete it */{
Temp = CursorSpace[P].Next;CursorSpace[P].Next = CursorSpace[Temp].Next;CursorFree(Temp);
}}
Routine to implement Insertion operation:
void insert (ElementType X, List L, Position P){
/* Insert after the position, P */Position Temp;Temp = CursorAlloc( );if (Temp = = 0)then
printf(“Fatal Error: Out of Space!!!”);CursorSpace[Temp].Element = X;CursorSpace[Temp].Next = CursorSpace[P].Next;CursorSpace[P].Next = Temp;
}
This program to implement all these operations of Cursor implementation of the list is a straightforward from the previous routines, which we leave as a exercise.
55
4.6.2 Source code for cursor based implementation of linked list:
/* Cursor implementation of Linked list */
#include <stdio.h>#define spacesize 10
/* place in the interface file */
struct node{ int element; int next;};struct node cursorspace[ spacesize ];
static int cursoralloc( void ){ int p; p = cursorspace[ 0 ].next; cursorspace[ 0 ].next = cursorspace[ p ].next; return p;}
static void cursorfree( int p ){ cursorspace[ p ].next = cursorspace[ 0 ].next; cursorspace[ 0 ].next = p;}
void initializecursorspace( void ){ int i; for( i = 0; i < spacesize; i++ ) { cursorspace[ i ].next = i + 1;
} cursorspace[ spacesize - 1 ].next = 0;}
/* return true if l is empty */int isempty(){ return cursorspace[0].next == 0;}
56
int islast( int p){ return cursorspace[ p ].next == 0;}int findprevious( int x){ int P; P = 0; while( cursorspace[ P ].next &&
cursorspace[ cursorspace[ P ].next ].element != x ) P = cursorspace[ P ].next; return P;}int find( int x){ int p; p = cursorspace[0].next; while( p && cursorspace[ p ].element != x ) p = cursorspace[ p ].next; return p;}void delete( int x){ int p, tmpcell; p = findprevious(x); if( !islast(p) ) /* assumption of header use */ { /* x is found; delete it */
tmpcell = cursorspace[ p ].next;cursorspace[ p ].next = cursorspace[ tmpcell ].next;cursorfree( tmpcell );
}}void insert( int x,int p ){ int tmpcell;
/* 1*/ tmpcell = cursoralloc( );/* 2*/ if( tmpcell == 0 )/* 3*/ fatalerror( "out of space!!!" );/* 4*/ cursorspace[ tmpcell ].element = x;/* 5*/ cursorspace[ tmpcell ].next = cursorspace[ p ].next;/* 6*/ cursorspace[ p ].next = tmpcell;
}void display(){
int p=cursorspace[0].next;while(p!=0)
57
{printf("/n%d",cursorspace[p].element);p=cursorspace[p].next;
}}
void main(){
int choice,no,pos=0;while(1){
clrscr();initializecursorspace();printf("1.find\n");printf("2.delete\n");printf("3.insert\n");printf("4.display\n");printf("5.exit\n");printf("enter your choice\n");scanf("%d",&choice);switch(choice){
case 1:printf("\nenter the no:");scanf("%d",&no);if(find(no))
printf("/n element found");else
printf("\nelement not found");break;
case 2: printf("\nenter the no:");scanf("%d",&no);delete(no);break;
case 3: printf("\nenter the no and its pos");scanf("%d%d",&no,&pos);insert(no,pos);break;
case 4: display();break;
case 5: exit(0);}
}}
58
CHAPTER 4 – LINKED LIST
Two Mark Questions - PART A
1. Define List ADT
A list is a sequence of zero or more elements of a given type. The list is represented as sequence of elements separated by comma.
A1, A2, A3,…., AN
Where, N > 0 and Ai is of type element.
List as an ADT: While considering the list as an Abstract Data type, must specify the items and operations of the list. The list can grow or shrink. The list can grow or shrink. The element in a list is represented by “last”.
2. What are the ways of implementing linked list?
The list can be implemented in the following ways:
1. Array implementation 2. Linked – list implementation3. Cursor implementation
3. What are the types of linked Lists?
There are three types of the linked lists, which are as follows.
iv) Singly Linked Listv) Doubly Linked Listvi) Circularly Linked List
4. How the singly linked list can be represented?
59
Node
NextData
NULL
Head
Node
5. How the doubly linked list can be represented?
Doubly linked list is a collection of nodes where nodes are connected by forwarded and backward link. The diagrammatic representation is shown below:
Each node in the doubly linked list contains 3 fields. The first field contains the address of the previous node. The second field contains the data The third field contains the address of the next node.
6. When Singly linked list can be represented as Circular linked List?
In a Singly linked list, all nodes are connected with forward links to the next nodes in the list. The last node has a next field, NULL. Inorder to implement the circularly linked list from singly linked list, the last node’s next field is connected to the first node of the list as shown below:
7. When Doubly linked list can be represented as Circular linked List?
In a doubly linked list, all nodes are connected with forward and backward links to the next and previous nodes respectively. The first node’s previous field and last node’s next field is NULL. Inorder to implement the circularly linked list from doubly linked list, the first node’s previous field is connected to the last node and last node’s next field is connected to the first node as shown below:
60
Head
1000
10 2000 20 3000 30 1000
2000 3000
1000
10 2000 20 3000 30 1000
2000 3000
8. Where Cursor implementation can be used?
The cursor implementation of lists is used by many languages such as BASIC and FORTAN that do not support pointers. The two important features of the cursor implementation of linked lists are as follows:
1. The data are stores in a collection of structures. Each structure contains data and a index to the next structure.
2. A new structure can be obtained from the system’s global memory by a call to CursorSpace array. To do this, we will keep a list (the FreeList) of cells that are not in any list. The list will use cell 0 as a header.
9. Write routine to implement the find operation using cursor implementation of list.
Position Find (ElementType X, List L){
Position P;P = CursorSpace[L].Next;while(P&&CursorSpace[P].Elemeny!=X)
P = CursorSpace[P].Next;return P;
}
10. Write routine to implement the Delete operation using cursor implementation of list
void Delete (ElementType X, List L){
Position P, Temp;P = FindPrev(X, L); // to find previous position of element to be deleted if (!IsLast(P, L)) /* If X is found, then delete it */{
Temp = CursorSpace[P].Next;CursorSpace[P].Next = CursorSpace[Temp].Next;CursorFree(Temp);
}}
11. Write routine to implement the Insert operation using cursor implementation of list
void insert (ElementType X, List L, Position P){
/* Insert after the position, P */Position Temp;Temp = CursorAlloc( );if (Temp = = 0)
61
printf(“Fatal Error: Out of Space!!!”);CursorSpace[Temp].Element = X;CursorSpace[Temp].Next = CursorSpace[P].Next;CursorSpace[P].Next = Temp;
}
REVIEW QUESTIONS - PART B
1. Explain the various operations of the List ADT with examples.
2. Write the program for the array implementation of lists
3. Explain in detail the operation of Singly linked list implementation
4. Write the program for the singly linked list implementation of lists
5. Explain in detail the operation of doubly linked list implementation
6. Write the program for the doubly linked list implementation of lists
7. Describe the cursor implementation of list with routines and examples
62