DATA STRUCTURES AND ALGORITHMS
DIGITAL ASSIGNMENT
1.Given a sorted doubly linked list of positive distinct elements, the task is to find pairs in
doubly linked list whose sum is equal to given value x, without using any extra space ?
CODE :
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define bool int
#define true 1
#define false 0
struct Node
{
int data;
struct Node *next, *prev;
};
void pairSum(struct Node *head, int x)
{
struct Node *first = head;
struct Node *second = head;
while (second->next != NULL)
second = second->next;
bool found = false;
while (first != NULL && second != NULL &&
first != second && second->next != first)
{
if ((first->data + second->data) == x)
{
found = true;
printf("(%d,%d)\n" , first->data , second->data);
first = first->next;
second = second->prev;
}
else
{
if ((first->data + second->data) < x)
first = first->next;
else
second = second->prev;
}
}
if (found == false)
printf("No pair found");
}
void insert(struct Node **head, int data)
{
struct Node *temp;
temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = data;
temp->next = temp->prev = NULL;
if (!(*head))
(*head) = temp;
else
{
temp->next = *head;
(*head)->prev = temp;
(*head) = temp;
}
}
int main()
{
struct Node *head = NULL;
int i , x , num;
printf("Give the value of x :");
scanf("%d" , &x);
printf("Enter the number of elements in the linked list : ");
scanf("%d" , &num);
for( i =0 ;i < num ; i++){
int n ;
printf("Enter the value of element %d :" , i+1 );
scanf("%d" , &n);
insert(&head , n);
}
pairSum(head, x);
return 0;}