Expe 3 (I) DS
Expe 3 (I) DS
3A. Create a program to detect and remove duplicates from a linked list.
ALGORITHM STEPS:
3.Outer loop: Loop through the list until current is NULL or its next is NULL.
4.Inner loop: For each node, iterate through the rest of the list with another pointer runner.
7.Move to next node: Move current to the next node in the list.
CODE:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
};
if (curr->data == curr->next->data) {
curr->next = next_next;
}
else
curr = curr->next;
return head;
node = node->next;
printf("\n");
new_node->data = new_data;
new_node->next = NULL;
return new_node;
int main() {
// 36->36->36->42->42->20
head->next = createNode(36);
head->next->next = createNode(36);
head->next->next->next = createNode(42);
head->next->next->next->next = createNode(42);
head->next->next->next->next->next = createNode(20);
printList(head);
head = removeDuplicates(head);
printList(head);
return 0;
OUTPUT:
36 36 36 42 42 20
36 42 20
3B. Implement a linked list to represent polynomials and perform addition.
Algorithm Steps:
addTerm Function:
* Input Parameters: Accepts the head of the polynomial (head), the coefficient of the new term
(coefficient), and the exponent of the new term (exponent).
* Allocate Memory: Allocates memory for a new term (temp) using malloc.
* If memory allocation fails, it prints an error message and exits the program.
* Initialize Term: Sets the coefficient and exponent of the new term to the given values and its next
pointer to NULL.
* If the polynomial is empty (i.e., head is NULL), makes this term the head of the polynomial.
® Otherwise, traverses the polynomial to the end and appends the new term to the end.
addPolynomials Function:
* Input Parameters: Accepts the heads of two polynomials (poly1 and poly2) to add them
Iterative Addition:
* If the exponents are equal, adds their coefficients and creates a new term with the sum.
* If the exponent of one polynomial is greater than the other, adds that polynomial's term to
the result.
* Adds any remaining terms from both polynomials (if any) to the result.
* Traversal and Display: Traverses the polynomial from the head to the end and displays each term
along with its coefficient and exponent.