0% found this document useful (0 votes)
10 views

CS18302 Unit 02 Notes Full

Uploaded by

2021cs0346
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

CS18302 Unit 02 Notes Full

Uploaded by

2021cs0346
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

1 LINEAR DATA STRUCTURES–LIST

1.1 INTRODUCTION
Computer Problem Solving is an intricate process which needs careful planning,
logical precision, persistence and attention. It can be a challenging, exciting and satisfying
experience which needs personal creativity and expression.
1.1.1 Terminologies Used
Program
A set of explicit and unambiguous instructions expressed in a programming language
is called a program.
Algorithm
The set of instructions corresponds to a solution to a problem that is independent
of any programming language is called an algorithm.

Input Algorithm Output

Figure 1.1 Problem solving


Input
The data which is fed into the system for processing is called as input.
Output
The data which represents the computer solution to the problem is called as an
output.
Eg.
Problem : Sum of two numbers
Input : a, b – numbers
Output : c – number
Algorithm : 1. Get two numbers a, b
2. Calculate c = a + b
3. Print c
1.2 Data Structures

1.1.2 Requirements for Solving Problems by Computer

 the solution must be specified with logical precision and in such detail. And its is
obvious that conscious depth of understanding is needed to design effective computer
algorithms.

 Knowledge of the problem

 Efficient way of designing the problem.

1.2 PROBLEM SOLVING

 Problem Solving is a creative process which needs systematization and


mechanization.

 This problem solving skills are now-a-days developed from the school days.

 There is no universal methods for problem solving.

The steps for finding the solution for a problem is as follows

(i) Problem definition phase

(ii) Started with a problem

(iii) Use of specific examples

(iv) Similarities among problems

(v) Working backwards from the solution.

1.2.1 Problem Definition Phase

 The success in solving a problem is examined only if the solution is appropriate to


the problem.

 The preliminary investigation about the problem is called as the problem definition
phase.

 The primary task of this phase is ‘what must be done’ rather than ‘hoe to do it’.

 Care must be taken to extract the defined tasks precisely.


Linear Data Structures–List 1.3

1.2.2 Getting Started on a Problem

 For solving a problem, there are many ways to solve and it has many solutions.

 ‘What can we do’ – after analyzing the problem has to be determined.


 Not to be more concerned about detail.
 The sooner you start coding your programs the longer it is going to take.
1.2.3 Use of Specific Examples
 A better way of starting a problem is to use some heuristics. This approach always
moves us to make a start on a problem by picking a specific example of the general
problem.
 It is much easier to workout details of a solution to a specific problem because the
relationship between the mechanism and the particular problem is clearly defined.
 Geometrical or Schematic diagrams representing certain aspects of the problem
can be usefully employed in many instances.
 It an ideal case, the specifications for our particular problem need to be examined
carefully to check whether proposed algorithm meet those requirements.
1.2.4 Similarities Among Problems
 Another approach in problem solving is by considering the past experience
compared with current problem.
 Make a check if there are any similarities between the current problem and other
problems. It will be a good habit if we follow the saying that ‘Learn from
Experience’.
 Too much study of the exiting solution may sometimes deviate the problem.
Sometimes it would be better if we found an indecent solution.
 A very good problem solver has to view a problem from a variety of angles.
1.2.5 Working Backwards from the Solution
 In some problems, we initially had the solution and then try to work backwards to
the starting conditions.
1.4 Data Structures

 Write down all the steps and explorations made during problem solving and go
along the paths ay systematize our investigations and avoid duplication of effort.
 The important and crucial thing of all in developing problem-solving skills is practice.
 Problem solving skill will be developed after working with many of the related
problems.

1.3 ABSTRACT DATA TYPE (ADT)


Modularity plays a vital role in program development. It has several advantages as
• Much easier to debug small routines than large routines.
• Easy to work on the program simultaneously.
An abstract data type (ADT) is a set of operations which are all mathematical
abstractions where the implementation is not visible to the user.
An abstract data type (ADT) is a specification of a set of data and the set of
operations that can be performed on the data. It is independent of various concrete
implementations.
Examples:
Array, List, Queue, Stack, String, Tree
An abstract data structure is an abstract storage for data defined in terms of the set
of operations to be performed on data and computational complexity for perfuming these
operations, regardless of the implementation in a concrete data structure.
Suppose the stack ADT has the following interfaces
long Stack_Create ( );
void Push (item);
void Pop ( );
void Delete (Stack);
This ADT can be used in the following ways as
long Stack;
struct St*S;
Stack = Stack_Create ( );
Push (S);
Display (Stack);
Pop (Stack);
Linear Data Structures–List 1.5

1.3.1 Advantages of ADTs


 A modification to a program needs change in one or more of its data structures.
Rewriting each procedure for a change is not desirable. Thus to separate the use
of a data structure from the details of its implementation leads to abstract data
types.
p=getnode();
printf(“Enter an Item to insert\n”);
scanf(“%d”,&x);
node[p].info=x;
node[p].next=-1;
while(True)
{
printf(“Add Node(Y/N)?:\n”);
fflush(stdin);
add=getchar();
if(add==’y’||add==’Y’)
{
printf(“\nEnter an item to insert:”);
scanf(“%d”,&x);
insert(p,x);
node[p].next=-1;
}
else
return;
}
}
// Display Routine
show()
{
p=0;
printf(“\nNode(P)\tInfo\tNext”);
while(node[p].next!=-1)
1.6 Data Structures

{
printf(“\n%d\t %d \t%d” ,p,node[p].info,node[p].next);
p=node[p].next;
}
//return;
printf(“\n%d \t %d \t%d”,p,node[p].info,node[p].next);
putchar(‘\n’);
return;
}

// Insertion Routine
insert(p,x)
{
int q;
if(p==-1)
{
printf(“\nVoid Insertion”);
return;
}
q=getnode();
node[q].info=x;
node[q].next=node[p].next;
node[p].next=q;
return;
}

// Deletion Routine
delete(p)
int p;
{
int q;
if(p==-1||node[p].next==-1)
{
Linear Data Structures–List 1.7

printf(“Void deletion”);
exit(1);
}
q=node[p].next;
freenode(q);
return;
}
1.4 LIST ADT
The list ADT is the data structure used to store the elements in an efficient way
where each element is linked with other elements by its address.
A list is of the form A1, A2 ……. AN

A1 A2 AN

First Last
Figure 1.2 Linked list

A1 500 A2 600 A3 902 A4 0


1000 500 600 902
address
Figure 1.3 Linked list with pointer values
A list with no item is called as an Empty list. For any list except empty list, it has the
data structure as follows
• Ai+1 follows Ai (i > n)
• Ai+1 precedes Ai (i > 1)
The first element is A1 and the last element is An. The position of element Ai in a list
is i. The major operations involved with the list ADT are as follows
• Insert
• Delete
• Find
• Printlist
• MakeEmpty
1.8 Data Structures

1.4.1 Array Implementation of List


All the operations can also be implemented using arrays. But there should be an
estimate of the maximum size while implementing a dynamic list. This may cause wastage
of memory.
The operations like PrintList and Find needs linear time executions since memory
is statically allocated.
Insertion and deletion are expensive in arrays because
Insertion – Pushing the entire array downwards to one step to make a
free space
Deletion of 
 – shifting all the elements in the list one step up.
I st element 
The worst case running time is
( ) PrintList
– Constant time
(ii) Find
(iii) Insertion
– O(N)
(iv) Deletion
Since the running time is slow and there is no dynamic allocation, arrays are generally
not used to implement lists.

Item Next
0 a 1
1 b 2 Linked list
2 c –1
3 4
4 5
5 6
6 7 Free List
7 8
.. ..
. .

Figure 1.4 Array based implementation of linked list


Linear Data Structures–List 1.9

The structure of a node is as follows,


struct Node {
char item;
int next;
} Node arraylist [10];
The operations that are possible with array based implementation of linked list are
as follows
Item Next Item Next Item Next
0 5 1 0 5 4 0 5 4
1 2 2 4 7 1 4 7 1
2 9 3 1 2 2 1 2 3
3 1 –1 2 9 3 2 5
4 3 1 –1 3 1 –1
5 5 5
6 –1 6 –1 6 –1
Initial Array Insert 7 after Delete after
index 0 index 2

Figure 1.5
// Get Node Routine
getnode()
{
if(avail==-1)
{
printf(“\nOverflow”);
exit(1);
}
p=avail;
avail=node[avail].next;
return(p);
}

// Releasing the Memory


1.10 Data Structures

freenode(p)
{
node[p].next=avail;
avail=p;
return;
}

// Node Creation Routine


create()
{
int x;
char add;
1.4.2 Linked List Implementation Using Pointers
The linked list structure consists of a series of structures which are not contiguous
in memory. Each structure has the value and a pointer to the next node.

10 400 10 – Value
1000 – Address
Address next 400 – Next Node’s address
1000 pointer
Figure 1.6 Pointer
And the node’s next pointer points to NULL (i.e 0 in ANSI C)
A pointer variable is a variable which contains the address of another variable. For
example, if P is declared as pointer, then the value stored in P is interpreted as the location in
main memory.
P  field name = value
P  next = address of the next node.
The running time of linked list using pointer is as follows
PrintList (L) – Linear time
But greater than array
Find (L, Key) – Linear time
Delete – O(1)
Insert – O(1)
Linear Data Structures–List 1.11

The Printlist (L) needs just a pointer to the first element in the list and then traverse
the list by following the next pointers.
Finding Kth element needs to traverse the list one by one till the null pointer.
The delete function can be executed in one pointer change.
P
A1 A2 A3 A4 0
Temp
Figure 1.7 Deleting the node A3
The Insert function can be executed by creating a node structure and traverse
down to the particular position and change the link to the necessary nodes.

A1 A2 A3 A4 0

Figure 1.8 Inserting the node x


1.4.3 Singly Linked List
While implementing the list, there are several special cases to be considered. Because
careless coding may lose the list.
The insertion of a node in the linked list may have 3 cases
1. Inserting a node at the front
2. Inserting a node at the last
3. Inserting a node in the Middle
This is also same for the deletion case. In order to reduce problem in List, Keep a
sentinel node referred to as a header or dummy node, it is placed in the position 0.
If a header is used, then it is possible to delete the first element in the list, Find
previous will return the position of the header.
1.12 Data Structures

The function declarations and prototypes are shown in Figure1.9 and 1.10.
# ifndef_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
Figure 1.9 Type declarations for linked list
// Node Declaration
struct Node
{
ElementType Element;
Position Next;
};

Figure 1.10 Linked List function declarations


Linear Data Structures–List 1.13

The function used to check the emptiness of a list is Empty() Shown in Figure 1.11.
int IsEmpty (List L)
{
return L  Next = = NULL;
}
Figure 1.11 To check the emptiness

header

Empty List L

The function IsLast( ) tests the current element whether it is in the last position or
not as shown in Figure 1.12.
int IsLast (Position P, List L)
{
return P  Next = = NULL
}
Figure 1.12 To check the node whether it is the last position
Then the function used to find the position of the list is Find( ) shown in Figure 1.13.
Position Find (ElementType X, List L)
{
Position P;
P = L  Next;
while (P! = NULL && P  Element ! = X)
P = P  Next;
return P;
}
Figure 1.13 Find function to find the position
1.14 Data Structures

Next the function for deleting a node is shown in Figure 14.


void Delete (ElementType X, List L)
{
Position P, temp;
P = FindPrevious (X, L); //in fig (12)
If (! IsLast (P, L))
{
temp = P  Next;
P  Next = temp  Next;
free (temp);
}
}
Figure 1.14 Deletion routine for linked list
This Delete( ) routine deletes the first occurrence of X and skip from the routine if
it is not in the List as shown in Figure 1.14. After deletion, the link has to be changed. So
that it is necessary to find the previous element by the function FindPrevious( ) shown in
Figure 1.15.
Next is the Insert( ) routine to insert an element at a particular location. For this also
the knowledge of the previous node is important and it is found out by FindPrevious( )
routine. The insert routine will insert the element after the position specified by P, shown in
Figure 1.15.
Position FindPrevious (ElementType X, List L)
{
Position P;
P = L;
while (P  Next! = NULL && P  Next  Element ! = X)
P = P  Next
return P;
}
Figure 1.15 Find routine for searching the previous element
Linear Data Structures–List 1.15

void Insert (ElementType X, List L, Position P);


{
Position temp;
Temp = malloc (sizeof (struct Node));
if (Temp = = NULL)
FatalError (“Out of space”);
Temp  Element = X;
Temp  Next = P  Next;
P  Next = temp;
}
Figure 1.16 Insert Routine to add an element after position P
The common errors encountered while dealing with pointers are given as follows
1. Memory access violation
2. Segmentation violation
3. Indirection Problems
So while using pointers, the things to be considered are
1. Initialize the variable.
2. Make sure that the pointer is not NULL while indirection.
3. Include the Library stdlib.h
4. After delete, each memory space has to be cleared by free( ) routine.
The right way to deleting a List is given in Figure 1.17.
void DeleteList (List L)
{
Postion P, temp;
P = L  Next;
L  Next = NULL;
1.16 Data Structures

while (P! = NULL)


{
temp = P  Next;
free (P);
P = temp;
}
}
Figure 1.17 Function to delete a list
In a linked list, traversal refers to accessing the nodes of the list to perform some
important function. By using the HEAD pointer, the first node of the list is identified and -1
is placed at the NEXT field of the last node.
The algorithm for traversing a linked list is shown in Figure 1.18
// Traversal of linked list
void Traversal (List L)
{
position P;
P = L  Next; // pointing HEAD node
while (P! = NULL)
P = P  Next;
}
Figure 1.18
Inserting node at the beginning

Start

temp

Figure 1.19 Inserting node at the begining


Linear Data Structures–List 1.17

Inserting a Node at Position P

Original List
First

2 4 6 8

List with 5 added


first

2 4 6 8

Figure 1.20 Inserting anode at Position P


Inserting a Node at the End

Head

A B C D
Data Next

tmp
E NULL

Figure 1.21 Inserting anode at Position P


Deleting a Node after ptr

Deleting node in linked list

First ptr temp = ptr.next ptr.next.next last

Figure 1.22 Deleting a node after ptr


1.18 Data Structures

1.5 CIRCULARLY LINKED LISTS

A cyclic movement is possible in the circularly Linked List where the cell keeps the
pointer back to the first.

N1 N2 N3 N4

Figure 1.23 Circularly linked list

All the operations involved with the linked List is also possible with the circularly
Linked Lists.

In order to keep the linked list to work in a circular way, the last node is pointed to
the first node of the list. There is no need of header for storing the beginning of a list. The
traversal of a circular list can begin at any node until pointing to the same node. There
may not be any beginning or end for the circular linked list.

Header
A B C D

Figure 1.24 Circular Linked List

These kind of lists are used in operating systems for task maintenance.

Example:

Moving forward/backward in a Browser. While browsing the internet, people used


to perform forward/backward using forward and backward button. This can be performed
by a circular linked list to maintain the sequence of the web pages visited.

Consider the memory representation of a circular linked list which is used to store
the details of student marks as shown in figure 1.21.
Linear Data Structures–List 1.19

Head Roll No Mark Next


1 C O1 50 7
2 CO5 70 1
3 CO3 30 6
4
5
6 CO4 45 2
7 CO2 79 3
8

Figure 1.25 Memory representation of circular linked list


It is also possible to maintain many linked lists simultaneously in the memory, by
maintaining a separate head pointer pointing the address of the first node of each lists.
The operations performed in the circular linked list are as follows,
(i) Inserting a new node at position P
(ii) Deleting a node at position P
(i) Inserting a new node at position P
When a new node is inserted at position P, the position needs to the identified first
and then insert the new element to the next of position P.
Position Find (int X, list L)
{
Position P, head;
head = P = L;
while (P  Next ! = head && P  Element ! = X)
{
P = P  Next;
}
return P;
}
void Insert (int X, List L, int Y)
{ // Y – element after X is inserted
1.20 Data Structures

Position temp, P;
P = Find (Y, L);
temp = malloc (size of (struct node));
if (L = = NULL)
printf (“cannot enter an element”);
temp  Element =X;
temp  Next = P  Next;
P  Next = temp;
}

10 20 30 50

List L

To insert a new node 40 after 30

10 20 30 40 50
P temp

(1) Call Find (30, list L), returns P


(2) Update P
temp  Element = x
temp  Next = P  Next
P  Next = temp
While inserting a node after node P, the next field of the node P is pointed to the
next field of new node and the next field of P node is pointed to the new node.
Deleting a node from a Circularly linked list:
i) The node to be deleted is positioned first and the previous node has to be identified.
ii) By changing the next of previous node to the next of node to be deleted.
Linear Data Structures–List 1.21

Algorithm
void Delete (int X, List L)
{
Position P, Tmpcell;
P = L; // pointing head node
if (P = = NULL)
printf (“Underflow”);
while (P  Next ! = L && P  Next  Element ! = X)
P = P  Next;
Tmpcell = P  Next;
P  Next = Tmpcell  Next;
free (Tmpcell);
}
L TemCell
P
10 20 30 40
temp

To Delete the node X, P represents the previous Node.

L P TempCell Next
10 20 30 40

P  Next = Tmpcell  Next;


free (Tmpcell);
If the deletion is performed at the beginning of the list.
If is necessary to check whether the head node is NULL or not. If it is not null, we
use the pointer P to traverse the list till the last node. And then change the next pointer of
the last node to point to the second node of the circular linked list. And then the memory
occupied by the first node is freed. And then make the first node initialized as the HEAD
of the list.
1.22 Data Structures

1.6 DOUBLY LINKED LIST

The restriction when using Linked List (singly) is that there is one way path available
to traverse down the list. For this, it is better to have a back pointer to solve this problem.

Thus the Linked list constructed with two pointers front and back which specifies
the link in forward and backward traversal is called as Doubly Linked List.

N1 N2 N3

Figure 1.26 Doubly linked list


The operations involved in this doubly Linkedlist is same as that of singly Linked
List. But the change is with the pointer operations.

Figure 1.27 Insertion


A doubly linked list is a more complex type of linked list which contains a pointer
to the next node as well as to the previous node of the list. Each node in a doubly linked
list consists of three fields,
(i) Element field or data field
(ii) A pointer to the next node
(iii) A pointer to the previous node

Prev Data Next


Structure of node in Doubly linked list

Head
NULL 1 2 3 NULL
Linear Data Structures–List 1.23

The structure of a doubly linked list is represented as


struct node
{
struct node *prev;
int data;
struct node *next;
};
struct node *Head NULL;
Here the prev field of the first node and the next field of the last node contains
NULL.
PREV – stores the address of preceding node
NEXT – stores the address of Next node
Thus the doubly linked list moves both in the forward and backward direction. It
doubles the cost of insertions and deletions since there are more pointers to fix.
The memory representation of doubly linked list is shown in Figure1.24.

Head Data Prev Next


1 10 –1 3
2 40 4 6
3 20 1 4
4 30 3 2
5
6 50 2 –1
7
Memory Representation
Figure 1.28 Memory representation
The operations that are performed in a doubly linked list are listed as follows
(i) Insertion at the beginning
(ii) Insertion at the end
(iii) Insertion after a node P
(iv) Insertion before a node P
1.24 Data Structures

(v) Deleting a node at the beginning


(vi) Deleting a node at the end
(vii) Deleting a node after a node P
(viii) Deleting a node before a node P
(i) Inserting a node at the beginning:
When the want to add a new node X at the beginning of the list, then the following
changes are to be preformed in the list,

Head
NULL 10 20 30 50 NULL
Old List
NULL 5 NULL New Node
X

Add the new node before the Head node. So the new node will be the Head node.
The next link of the new node should point to the first node of the old list.
Head
NULL 5 10 20 30 40
New List
void insertatBegin (List L, int X)
{
node* temp;
temp = malloc (sizeof (struct node));
if (L = = NULL)
printf (“No node in the list”)”
temp  data = X;
temp  prev = NULL;
temp  Next = L; // pointing Head L
L  Prev = temp;
L = temp;
}
Linear Data Structures–List 1.25

(ii) Inserting a node at End of a Double linked List


When a new node X is inserted at the end of the list, the following changes have to
be performed.

Head
NULL 10 20 30 40 NULL

2
X New List

After Insertion
Head
NULL 10 20 30 40 2 NULL

void insertatEnd (List L, int X)


{
node* temp;
temp = (struct node*) malloc (size of (struct node));
temp  data = x;
P = L;
while (p  next ! = NULL)
P = P  next;
P  next = temp;
temp  prev = P;
temp  next = NULL;
}
Traverse till the end of the doubly linked list, when the last node is reached, change
the next pointer of the last node to store the address of the new node. And make the next
of the new node as NULL to signify the last node.
The prev field of the new node is pointed to the address of the last node in the
old list.
1.26 Data Structures

(i) Inserting a Node X after a given node P


Suppose we want to add a new node X after a node P, then search for the position
P, then store the next value of the P node and the prev value of the next node of P. The
logical steps are listed as follows,
void Insertatposition (List L, int X, int Y)
{
node* temp, head, P;
temp = (struct node*) malloc (sizeof (struct node));
temp  data = x;
head = P = L;
while (P  Next ! = NULL && P  data ! = Y)
P = P  Next;
temp  Next = P  Next;
temp  prev = P;
P  Next = temp;
temp  Next  Prev = temp;
}

Head P
NULL 10 20 30 40 NULL

Doubly Linked List


To insert 25 after 20.
25 temp

Call InsertatPosition (L, 25, 20)


temp  data = 25
temp  Next = P  Next
temp  Prev = P
P  Next = temp
temp  Next  Prev = temp
Linear Data Structures–List 1.27

From the Algorithm, we start from the Head node of the linked list. We initialize the
head node with pointer P, then traverse the linked list to reach the node that has its data
equal to Y. Once the node is reached, the next of the new node is copied with the next of
P node. The prev link of the new node is pointed to the P node. And the next of the P
node is pointed to the new node. Finally the prev link of the next of the new node is
pointed to the newnode.
Deletion
In this section, how a node is deleted from a doubly linked list is demonstrated.
While deleting a node from a list, the operations that are to be performed are as
follows.

Head Delete node after 20

NULL 10 20 30 40 NULL
P node to be
deleted

temp = P  Next  Next


P  Next = Temp
temp  Prev = P

Head
NULL 10 20 40 NULL
After deleting the node 30

To delete a node from a doubly linked list,


(i) Check whether the list is empty or not. Goto step 2, if the list is not empty.
(ii) Set the head pointer to the P node.
(iii) Traverse through the list, make the next field of the P node in a list to the next
of the prev field of P node.
(iv) Release the memory of the deleted node.
1.28 Data Structures

void Delete (int X, List L)


{
Position P, Tmpcell;
P = L; //pointing head node
if (P = = NULL)
printf (“Underflow”);
while ((P  Next ! = – 1) && (P  Next  data ! = X))
P = P  Next;
Tmpcell = P  Next;
P  Next = Tmpcell  Next;
Tmpcell  Next  Prev = P;
free (Tmpcell);
}

1.7 APPLICATIONS OF LINKED LISTS


All kinds of dynamic allocation related problems can be solved using Linked Lists.
Some of the applications are given below
• Polynomial ADT
• Radix Sort
• Multi Lists
Polynomial ADT
An abstract data type for Single – variable polynomial has been constructed
using List.
The general form of polynomial is given by
f(x) = an xn + an–1 xn–1 + …. a1 x + a0
This can be implemented using Linked Lists. All operations like addition, subtraction,
multiplication are all possible using the List.
Linear Data Structures–List 1.29

The array implementation of the polynomial ADT is given in Figure 1.29.

typedef struct
{
int CoeffArray [maxdegree+1];
int Highpower;
} *Polynomial;
//Initialize the resultant polynomial to Zero
void Zeropolynomial (Polynomial P)
{
int i;
for (i=0; i  Maxdegree; i++)
P  CoeffArray [i] = 0;
P  Highpower = 0;
}
// Routine to add two Polynomials
void Addpoly(const Polynomial P1, const Polynomial P2, Polynomial Sum)
{
int i;
ZeroPolynomial (Sum);
Sum  Highpower = Max (P1  Hight Power, P2  HighPower);
for (i=Sum  Highpower; i>=0; i– –)
Sum  CoeffArray [i] = P1  CoeffArray [i] + P2  CoeffArray [i];
}
Figure 1.29 Polynomial ADT
The linked list representation of the polynomial ADT is shown as follows
Let P1 = 5x10 + 4x7 + 1
P2 = 6x25 + 8x5 + 2x
1.30 Data Structures

p1 5 10 4 7 1 0

p2 6 25 8 5 2 1

And the node declaration for this Linked List implementation is given as follows

typedef struct Node *PtrToNode;


struct Node
{
int Coefficient;
int Exponent;
PtrToNode Next;
}
typedef PtrToNode Polynomial;

Figure 1.30 Linked list representation of polynomial ADT


Each Co-efficient in the polynomial is stored in one cell, provided the cells are
sorted in decreased order of their exponents.
Linear Data Structures–List 1.31

REVIEW QUESTIONS
Example: 1
Reverse of a Singly Linked List with iterations
voidreverse_list()
{
node *p, *q, *r;
if (head = = (mynode *)0)
{ return; }
p = head;
q = p  next;
p  next = (mynode *)0;
while (q != (mynode *)0)
{
r = q  next;
q  next = p;
p = q;
q = r;
}
head = p;
}
Example: 2
Reverse of a Singly Linked List with Recursion
node* reverse_list(mynode *root)
{
if(root  next! = (mynode *)0)
{
reverse_list(root  next);
root  next  next = root;
return(root);
}
else
{ head = root; }
}
1.32 Data Structures

Example: 3
Reverse of a Doubly Linked List
void reverse( )
{
node *cur, *temp, *nextnode;
if(head == tail)
return;
if(head == NULL || tail == NULL)
return;
for(cur = head; cur! = NULL; )
{
temp = cur  next;
nextnode = cur  next;
cur  next = cur  prev;
cur  prev = temp;
cur = nextnode;
}
temp = head;
head = tail;
tail = temp;
}
Example: 4
Finding the middle of a Linked List
struct node *middle(struct node *head)
{
p = head;
q = head;
while(q  next  next! = NULL)
{
p = p  next;
q = q  next  next;
}
return p;
}

You might also like