Upload files to "DS/C/Lab/Week8"
This commit is contained in:
parent
75507b7abc
commit
e9a4ce08c7
4 changed files with 506 additions and 0 deletions
90
DS/C/Lab/Week8/DLLUnionIntersec.c
Normal file
90
DS/C/Lab/Week8/DLLUnionIntersec.c
Normal file
|
@ -0,0 +1,90 @@
|
|||
// Write a program to implement union and intersection of two doubly linked lists.
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
struct node {
|
||||
int data;
|
||||
struct node *prev;
|
||||
struct node *next;
|
||||
};
|
||||
|
||||
typedef struct node *NODE;
|
||||
|
||||
NODE getnode() {
|
||||
NODE x;
|
||||
x = (NODE)malloc(sizeof(struct node));
|
||||
if(x == NULL) {
|
||||
printf("Out of memory\n");
|
||||
exit(0);
|
||||
}
|
||||
return x;
|
||||
}
|
||||
|
||||
void insert_rear(NODE *head, int item) {
|
||||
NODE temp, cur;
|
||||
temp = getnode();
|
||||
temp->data = item;
|
||||
temp->next = NULL;
|
||||
if(*head == NULL) {
|
||||
temp->prev = NULL;
|
||||
*head = temp;
|
||||
return;
|
||||
}
|
||||
cur = *head;
|
||||
while(cur->next != NULL)
|
||||
cur = cur->next;
|
||||
cur->next = temp;
|
||||
temp->prev = cur;
|
||||
}
|
||||
|
||||
NODE union_lists(NODE head1, NODE head2) {
|
||||
NODE result = NULL;
|
||||
NODE temp = head1;
|
||||
while(temp != NULL) {
|
||||
insert_rear(&result, temp->data);
|
||||
temp = temp->next;
|
||||
}
|
||||
temp = head2;
|
||||
while(temp != NULL) {
|
||||
NODE cur = result;
|
||||
int found = 0;
|
||||
while(cur != NULL) {
|
||||
if(cur->data == temp->data) {
|
||||
found = 1;
|
||||
break;
|
||||
}
|
||||
cur = cur->next;
|
||||
}
|
||||
if(!found)
|
||||
insert_rear(&result, temp->data);
|
||||
temp = temp->next;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
NODE intersection_lists(NODE head1, NODE head2) {
|
||||
NODE result = NULL;
|
||||
NODE temp = head1;
|
||||
while(temp != NULL) {
|
||||
NODE cur = head2;
|
||||
while(cur != NULL) {
|
||||
if(temp->data == cur->data) {
|
||||
insert_rear(&result, temp->data);
|
||||
break;
|
||||
}
|
||||
cur = cur->next;
|
||||
}
|
||||
temp = temp->next;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
void display(NODE head) {
|
||||
NODE temp = head;
|
||||
while(temp != NULL) {
|
||||
printf("%d ", temp->data);
|
||||
temp = temp->next;
|
||||
}
|
||||
printf("\n");
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue