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

DSPD Unit - III Notes PDF

The document discusses singly linked lists in C. It defines a node as having a data part and next part pointing to the next node. A linked list is formed by linking many such nodes together in a chain with the first node as the head. Functions are provided to create a node, add a node, traverse the list, insert at the front/middle/end, and delete from the front/middle/end. Code examples are given to demonstrate creating a sample linked list and calling the various functions to manipulate the list.

Uploaded by

Tanay Faye
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
91 views

DSPD Unit - III Notes PDF

The document discusses singly linked lists in C. It defines a node as having a data part and next part pointing to the next node. A linked list is formed by linking many such nodes together in a chain with the first node as the head. Functions are provided to create a node, add a node, traverse the list, insert at the front/middle/end, and delete from the front/middle/end. Code examples are given to demonstrate creating a sample linked list and calling the various functions to manipulate the list.

Uploaded by

Tanay Faye
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

UNIT-III Sub.- DSPD Sem/Br.

- 4th /CT

Singly Linked List

A linked list is a way to store a collection of elements. Like an array these can be character
or integers. Each element in a linked list is stored in the form of a node.

Node:

A node is a collection of two sub-elements or parts. A data part that stores the element and
a next part that stores the link to the next node.

Linked List:

A linked list is formed when many such nodes are linked together to form a chain. Each
node points to the next node present in the order. The first node is always used as a
reference to traverse the list and is called HEAD. The last node points to NULL.

Declaring a Linked list :

In C language, a linked list can be implemented using structure and pointers.


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

The above definition is used to create every node in the list. The data field stores the
element and the next is a pointer to store the address of the next node.

In place of a data type, struct LinkedList is written before next. That's because its a self-
referencing pointer. It means a pointer that points to whatever it is a part of. Here next is a
part of a node and it will point to the next node.

Creating a Node:

Let's define a data type of struct LinkedList to make code cleaner.


typedef struct LinkedList *node; //Define node as pointer of data type struct
LinkedList

node createNode(){
node temp; // declare a node

 By Prof. Saurabh P. Ratnaparkhi


UNIT-III Sub.- DSPD Sem/Br.- 4th /CT

temp = (node)malloc(sizeof(struct LinkedList)); //allocate memory using


malloc()
temp->next = NULL;// make next point to NULL
return temp;//return the new node
}

typedef is used to define a data type in C.

malloc() is used to dynamically allocate a single block of memory in C, it is available in the


header file stdlib.h.

sizeof() is used to determine size in bytes of an element in C. Here it is used to determine size
of each node and sent as a parameter to malloc.

Note:- The above code will create a node with data as value and next pointing to NULL.

To add a node to the linked list:


node addNode(node head, int value)
{
node temp,p;// declare two nodes temp and p
temp = createNode();//createNode will return a new node with data = value
and next pointing to NULL.
temp->data = value; // add element's value to data part of node
if(head == NULL)
{
head = temp; //when linked list is empty
}
Else
{
p = head;//assign head to p
while(p->next != NULL)
{
p = p->next; //traverse the list until p is the last node.
// The last node always points to NULL.
}
p->next = temp;//Point the previous last node to the new node
created.
}
return head;
}

Here the new node will always be added after the last node. This is known as inserting a
node at the rear end.

Food for thought


This type of linked list is known as simple or singly linked list. A simple linked list can be
traversed in only one direction from head to the last node.
The last node is checked by the condition:
p->next = NULL;

Here -> is used to access next sub element of node p. NULL denotes no node exists after
the current node , i.e. its the end of the list.

 By Prof. Saurabh P. Ratnaparkhi


UNIT-III Sub.- DSPD Sem/Br.- 4th /CT

Traversing the list:


The linked list can be traversed in a while loop by using the head node as a starting
reference:

node p;
p = head;
While (p != NULL)
{
p = p->next;
}

Singly Linked List Insertion and deletion function program in C


#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next; Add to beginning
};
 Allocate memory for new
void display(struct node* head)
node
{
struct node *temp = head;  Store data
printf("\n\nList elements are - \n");  Change next of new node
while(temp != NULL) to point to head
{  Change head to point to
printf("%d --->",temp->data); recently created node
temp = temp->next;
}
}

void insertAtFront(struct node** headRef, int value) Add to middle


{
struct node* head = *headRef;
 Allocate memory and
struct node *newNode; store data for new node
newNode = malloc(sizeof(struct node));  Traverse to node just
newNode->data = value; before the required
newNode->next = head; position of new node
head = newNode;  Change next pointers to
include new node in
*headRef = head; between
}

void insertAtMiddle(struct node *head, int position, int value)


{
struct node *temp = head;
struct node *newNode;
newNode = malloc(sizeof(struct node));
newNode->data = value;

int i;

for(i=2; i<position; i++)


{
if (temp->next != NULL)
{
temp = temp->next;

 By Prof. Saurabh P. Ratnaparkhi


UNIT-III Sub.- DSPD Sem/Br.- 4th /CT

}
}
newNode->next = temp->next;
temp->next = newNode;
}
Add to end
void insertAtEnd(struct node* head, int value)
{  Allocate memory for new
struct node *newNode; node
newNode = malloc(sizeof(struct node));  Store data
newNode->data = value;
 Traverse to last node
newNode->next = NULL;
 Change next of last node
struct node *temp = head; to recently created node
while(temp->next != NULL){
temp = temp->next;
}
temp->next = newNode;
}

void deleteFromFront(struct node** headRef) Delete from beginning


{  Point head to the second
struct node* head = *headRef;
node
head = head->next;
*headRef = head;
} Delete from end
 Traverse to second last
void deleteFromEnd(struct node* head) element
{
 Change its next pointer
struct node* temp = head;
while(temp->next->next!=NULL){ to null
temp = temp->next; Delete from middle
}  Traverse to element
temp->next = NULL; before the element to be
} deleted
 Change next pointers to
void deleteFromMiddle(struct node* head, int position)
{
exclude the node from
struct node* temp = head; the chain
int i;
for(i=2;i<position; i++)
{ if(temp->next != NULL)
{
temp = temp->next;
}
}
temp->next = temp->next->next;
}

int main() {
/* Initialize nodes */
struct node *head;
struct node *one = NULL;
struct node *two = NULL;
struct node *three = NULL;

/* Allocate memory */
one = malloc(sizeof(struct node));
two = malloc(sizeof(struct node));
three = malloc(sizeof(struct node));

 By Prof. Saurabh P. Ratnaparkhi


UNIT-III Sub.- DSPD Sem/Br.- 4th /CT

/* Assign data values */


one->data = 1;
two->data = 2;
three->data = 3;

/* Connect nodes */
one->next = two;
two->next = three;
three->next = NULL;

/* Save address of first node in head */


head = one;

display(head); // 1 --->2 --->3 --->

insertAtFront(&head, 4);
display(head); // 4 --->1 --->2 --->3 --->

deleteFromFront(&head);
display(head); // 1 --->2 --->3 --->

insertAtEnd(head, 5);
display(head); // 1 --->2 --->3 --->5 --->

deleteFromEnd(head);
display(head); // 1 --->2 --->3 --->

int position = 3;
insertAtMiddle(head, position, 10);
display(head); // 1 --->2 --->10 --->3 --->

deleteFromMiddle(head, position);
display(head); // 1 --->2 --->3 --->

How to traverse a linked list


Displaying the contents of a linked list is very simple. We keep moving the temp node to the
next one and display its contents.

When temp is NULL, we know that we have reached the end of linked list so we get out of the
while loop.

struct node *temp = head;


printf("\n\nList elements are - \n");
while(temp != NULL)
{
printf("%d --->",temp->data);
temp = temp->next;
}

The output of this program will be:

List elements are -


1 --->2 --->3 --->

 By Prof. Saurabh P. Ratnaparkhi


UNIT-III Sub.- DSPD Sem/Br.- 4th /CT

Polynomial Addition Using Structure with C program

A polynomial may be represented using array or structure. A structure may be defined such that
it contains two parts – one is the coefficient and second is the corresponding exponent. The
structure definition may be given as shown below:
Struct polynomial{
int coefficient;
int exponent;
};
The basic idea of polynomial addition is to add coefficient parts of the polynomials having same
exponent.
Algorithm:
AddPoly(Struct Poly p1[10],Struct Poly p2[10],int t1,int t2,Struct Poly
p3[10])
1.) [Initialize segment variables] [Initialize Counter] Set i=0,j=0,k=0

2.) Repeat step 3 while i<t1 and j<t2 Algorithm to add two polynomials using linked list is as
follows:-
3.) If p1[i].expo=p2[j].expo, then Let p and q be the two polynomials represented by
p3[i].coeff=p1[i].coeff+p2[i].coeff linked lists
p3[k].expo=p1[i].expo 1 . while p and q are not null, repeat step 2.
[Increase counter] Set i=i+1,j=j+1,k=k+1 2. If powers of the two terms ate equal then
else if p1[i].expo > p2[j].expo, then if the terms do not cancel then
p3[k].coeff=p1[i].coeff insert the sum of the terms into the sum
p3[k].expo=p1[i].expo Polynomial
[Increase counter] Set i=i+1,k=k+1 Advance p
else Advance q
p3[k].coeff=p2[j].coeff Else if the power of the first polynomial> power of
p3[k].expo=p2[j].expo second Then
Set j=j+1,k=k+1 insert the term from first polynomial into sum
[End of If] polynomial
[End of loop] Advance p
Else insert the term from second polynomial into sum
4.) Repeat while i<t1 polynomial
p3[k].coeff=p1[i].coeff Advance q
p3[k].expo=p1[i].expo 3. copy the remaining terms from the non empty
Set i=i+1,k=k+1 polynomial into the sum polynomial.
[End of loop] The third step of the algorithm is to be processed till the
end of the polynomials has not been reached.
5.) Repeat while j<t2
p3[k].coeff=p2[j].coeff
p3[k].expo=p2[j].expo

 By Prof. Saurabh P. Ratnaparkhi


UNIT-III Sub.- DSPD Sem/Br.- 4th /CT

Set j=j+1,k=k+1
[End of loop]

6.) Return k
7.) Exit

// Node structure containing power and coefficient of variable


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

// Function to create new node


void create_node(int x, int y, struct Node **temp)
{
struct Node *r, *z;
z = *temp;
if(z == NULL)
{
r =(struct Node*)malloc(sizeof(struct Node));
r->coeff = x;
r->pow = y;
*temp = r;
r->next = (struct Node*)malloc(sizeof(struct Node));
r = r->next;
r->next = NULL;
}
else
{
r->coeff = x;
r->pow = y;
r->next = (struct Node*)malloc(sizeof(struct Node));
r = r->next;
r->next = NULL;
}
}

C program for Polynomial Addition Using Structure


/* polynomial are stored using structure and program uses array of structure */
#include<stdio.h>

/* declare structure for polynomial */


struct poly
{
int coeff;
int expo;
};

 By Prof. Saurabh P. Ratnaparkhi


UNIT-III Sub.- DSPD Sem/Br.- 4th /CT

/* declare three arrays p1, p2, p3 of type structure poly. each polynomial can have maximum of ten
terms
/ * addition result of p1 and p2 is stored in p3 */

struct poly p1[10],p2[10],p3[10];

/* function prototypes */
int readPoly(struct poly []);
int addPoly(struct poly [],struct poly [],int ,int ,struct poly []);
void displayPoly( struct poly [],int terms);

int main()
{
int t1,t2,t3;

/* read and display first polynomial */


t1=readPoly(p1);
printf(" \n First polynomial : ");
displayPoly(p1,t1);
/* read and display second polynomial */
t2=readPoly(p2);
printf(" \n Second polynomial : ");
displayPoly(p2,t2);

/* add two polynomials and display resultant polynomial */


t3=addPoly(p1,p2,t1,t2,p3);
printf(" \n\n Resultant polynomial after addition : ");
displayPoly(p3,t3);
printf("\n");

return 0;
}

int readPoly(struct poly p[10])


{
int t1,i;

printf("\n\n Enter the total number of terms in the polynomial:");


scanf("%d",&t1);

printf("\n Enter the COEFFICIENT and EXPONENT in DESCENDING ORDER\n");


for(i=0;i<t1;i++)
{
printf(" Enter the Coefficient(%d): ",i+1);
scanf("%d",&p[i].coeff);

 By Prof. Saurabh P. Ratnaparkhi


UNIT-III Sub.- DSPD Sem/Br.- 4th /CT

printf(" Enter the exponent(%d): ",i+1);


scanf("%d",&p[i].expo); /* only statement in loop */
}
return(t1);
}

int addPoly(struct poly p1[10],struct poly p2[10],int t1,int t2,struct poly p3[10])
{
int i,j,k;

i=0;
j=0;
k=0;

while(i<t1 && j<t2)


{
if(p1[i].expo==p2[j].expo)
{
p3[k].coeff=p1[i].coeff + p2[j].coeff;
p3[k].expo=p1[i].expo;

i++;
j++;
k++;
}
else if(p1[i].expo>p2[j].expo)
{
p3[k].coeff=p1[i].coeff;
p3[k].expo=p1[i].expo;
i++;
k++;
}
else
{
p3[k].coeff=p2[j].coeff;
p3[k].expo=p2[j].expo;
j++;
k++;
}
}

/* for rest over terms of polynomial 1 */


while(i<t1)
{

 By Prof. Saurabh P. Ratnaparkhi


UNIT-III Sub.- DSPD Sem/Br.- 4th /CT

p3[k].coeff=p1[i].coeff;
p3[k].expo=p1[i].expo;
i++;
k++;
}
/* for rest over terms of polynomial 2 */
while(j<t2)
{
p3[k].coeff=p2[j].coeff;
p3[k].expo=p2[j].expo;
j++;
k++;
}

return(k); /* k is number of terms in resultant polynomial*/


}

void displayPoly(struct poly p[10],int term)


{
int k;

for(k=0;k<term-1;k++)
printf("%d(x^%d)+",p[k].coeff,p[k].expo);
printf("%d(x^%d)",p[term-1].coeff,p[term-1].expo);
}

To print DLL in reverse order

DoublyLinkedListNode* current =head;


DoublyLinkedListNode* temp ;
if(!head){
return head;
}
while(current->next!=NULL){
temp=current->next;
current->next=current->prev;
current->prev=temp;
current=temp;
}
current->next =current->prev;
current->prev=NULL;
head = current;
return head;

Display Doubly Linked List In Reverse

#include <stdio.h>
#include <stdlib.h>

 By Prof. Saurabh P. Ratnaparkhi


UNIT-III Sub.- DSPD Sem/Br.- 4th /CT

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

struct node *head = NULL;


struct node *last = NULL;

struct node *current = NULL;

//display the list


void printList() {
struct node *ptr = head;

printf("\n[head] <=>");
//start from the beginning
while(ptr != NULL) {
printf(" %d <=>",ptr->data);
ptr = ptr->next;
}

printf(" [last]\n");
}

//display the list


void print_backward() {
struct node *ptr = last;

printf("\n[head] <=>");
//start from the beginning
while(ptr != NULL) {
printf(" %d <=>",ptr->data);
ptr = ptr->prev;
}
printf(" [last]\n");
}

//Create Linked List


void insert(int data) {
// Allocate memory for new node;
struct node *link = (struct node*) malloc(sizeof(struct node));

link->data = data;
link->prev = NULL;
link->next = NULL;

// If head is empty, create new list


if(head==NULL) {
head = link;
return;
}

current = head;

// move to the end of the list


while(current->next!=NULL)
current = current->next;

// Insert link at the end of the list


current->next = link;

 By Prof. Saurabh P. Ratnaparkhi


UNIT-III Sub.- DSPD Sem/Br.- 4th /CT

last = link;
link->prev = current;
}

int main() {
insert(10);
insert(20);
insert(30);
insert(1);
insert(40);
insert(56);

printList();
print_backward();

return 0;
}

 By Prof. Saurabh P. Ratnaparkhi

You might also like