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

Lab 11 Solutions

The document provides a detailed guide on implementing various data structures and algorithms in C, including a stack using a linked list, adding two numbers using linked lists, and understanding doubly linked lists. It includes code examples for each task, demonstrating how to create, manipulate, and display linked lists, as well as handling polynomial representations. Additionally, it outlines optional tasks such as implementing a sparse polynomial using linked lists.

Uploaded by

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

Lab 11 Solutions

The document provides a detailed guide on implementing various data structures and algorithms in C, including a stack using a linked list, adding two numbers using linked lists, and understanding doubly linked lists. It includes code examples for each task, demonstrating how to create, manipulate, and display linked lists, as well as handling polynomial representations. Additionally, it outlines optional tasks such as implementing a sparse polynomial using linked lists.

Uploaded by

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

CS1100 : Introduction to Programming (Lab 11)

1. Stack Using Linked List: A stack is a linear data structure that follows the Last-In-First-Out (LIFO) principle. This
means that the last element added to the stack is the first one to be removed. You can think of it like a stack of books or
plates — the one placed last is removed first.
In this problem, you are required to implement a menu-driven C program to perform stack operations using a singly
linked list.

1. Define a structure named Node with:


• An integer field data
• A pointer to the next node
2. Implement the following functions:
(a) Push function — Adds a new element to the top of the stack.
(b) Pop function — Removes the top element from the stack and displays it. If the stack is empty, display Stack
Underflow.
(c) Display function — Displays all elements in the stack from top to bottom. If the stack is empty, display
Stack is empty.
3. In the main() function, repeatedly show a menu with the following choices until the user chooses to exit:
• 1 → Push
• 2 → Pop
• 3 → Display
• 4 → Exit
Prompt the user to enter their choice and call the appropriate function accordingly.

Examples:
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter value to push: 10
10 pushed to stack

1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 1
Enter value to push: 20
20 pushed to stack
1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 3
Stack elements:
20
10

1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 2
20 popped from stack

1. Push
2. Pop
3. Display
4. Exit
Enter your choice: 4
Program exited.

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

// Define the node structure


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

// Top of the stack


struct Node* top = NULL;

// Push function
void push(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (!newNode) {
printf("Memory allocation failed\n");
return;
}
newNode->data = value;
newNode->next = top;
top = newNode;
printf("%d pushed to stack\n", value);
}

// Pop function
void pop() {
if (top == NULL) {
printf("Stack Underflow\n");
return;
}
struct Node* temp = top;
printf("%d popped from stack\n", top->data);
top = top->next;
free(temp);
}

// Display function
void display() {
if (top == NULL) {
printf("Stack is empty\n");
return;
}
printf("Stack elements:\n");
struct Node* current = top;
while (current != NULL) {
printf("%d\n", current->data);
current = current->next;
}
}

// Main menu
int main() {
int choice, value;
while (1) {
printf("\n1. Push\n2. Pop\n3. Display\n4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter value to push: ");
scanf("%d", &value);
push(value);
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
printf("Program exited.\n");
return 0;
default:
printf("Invalid choice. Try again.\n");
}
}
return 0;
}

2. Adding Two Numbers Using Linked Lists: Write a C program that does the following:

1. Takes two non-negative integers as input from the user.


2. Extracts the digits of each number and store them in two separate singly linked lists.
3. Assumes that both numbers have the same number of digits.
4. Adds the two linked lists digit by digit and stores the result in a new linked list.
5. Prints the final sum from the new linkedlist.

Input Format:

• Two non-negative integers of the same number of digits.

Output Format:

• A single integer representing the sum of the two numbers.

Example:

Input:
Enter first number: 123
Enter second number: 456

Output:
Sum: 579

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

typedef struct Node {


int data;
struct Node* next;
} Node;

// Function to create a new node


Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}

// Insert at the end of the list


Node* insertAtEnd(Node* head, int data) {
Node* newNode = createNode(data);
if (head == NULL)
return newNode;
Node* temp = head;
while (temp->next != NULL)
temp = temp->next;
temp->next = newNode;
return head;
}

// Convert number to linked list with digits in reverse order


Node* numberToList(int num) {
Node* head = NULL;
if (num == 0) return createNode(0); // handle 0 explicitly
while (num > 0) {
head = insertAtEnd(head, num % 10);
num /= 10;
}
return head;
}

// Print the linked list


// Function to print the linked list in reverse (for correct order)
void printList(Node* head) {
if (head == NULL) return;
printList(head->next);
printf("%d", head->data);
}

// Add two linked lists representing numbers


Node* addLists(Node* l1, Node* l2) {
Node* result = NULL;
int carry = 0;

while (l1 != NULL || l2 != NULL || carry != 0) {


int sum = carry;
if (l1 != NULL) {
sum += l1->data;
l1 = l1->next;
}
if (l2 != NULL) {
sum += l2->data;
l2 = l2->next;
}

carry = sum / 10;


result = insertAtEnd(result, sum % 10);
}

return result;
}

int main() {
int num1, num2;
printf("Enter first number: ");
scanf("%d", &num1);

printf("Enter second number: ");


scanf("%d", &num2);

Node* l1 = numberToList(num1);
Node* l2 = numberToList(num2);

printf("First number (as list): ");


printList(l1);
printf("\n");

printf("Second number (as list): ");


printList(l2);
printf("\n");

Node* sum = addLists(l1, l2);

printf("Sum (as list): ");


printList(sum);

return 0;
}
3. Understanding Doubly Linked List:
A Doubly Linked List is a linear data structure where each element (called a node) contains three parts:

• data – stores the actual value,


• next – a pointer to the next node in the list,
• prev – a pointer to the previous node in the list.

This allows traversal of the list in both directions: from head to tail and from tail to head.
The structure of a node is typically defined as:

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

Important Notes:

• The prev pointer of the first node is NULL, as there is no node before it.
• The next pointer of the last node is NULL, as there is no node after it.

Your Task: Write a C program that performs the following:

1. Accepts n integers from the user (Take n also as input from user).
2. Creates a Doubly Linked List using the input values.
3. Prints the list in forward direction (left to right).
4. Prints the list in backward direction (right to left).

Example:

Input:
Enter number of elements: 5
Enter elements: 10 20 30 40 50

Output:
Output:
Forward: 10 20 30 40 50
Backward: 50 40 30 20 10

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

// Node structure for a doubly linked list


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

// Function to create a new node


struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}

// Function to insert at the end of the doubly linked list


struct Node* insertEnd(struct Node* head, int data) {
struct Node* newNode = createNode(data);
if (head == NULL) {
return newNode;
}
struct Node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
newNode->prev = temp;
return head;
}

// Function to print the list in forward direction


void printForward(struct Node* head) {
struct Node* temp = head;
printf("Forward: ");
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}

// Function to print the list in backward direction


void printBackward(struct Node* head) {
struct Node* temp = head;
if (temp == NULL) return;

// Go to the last node


while (temp->next != NULL) {
temp = temp->next;
}

printf("Backward: ");
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->prev;
}
printf("\n");
}

int main() {
struct Node* head = NULL;
int n, value;

printf("Enter number of elements: ");


scanf("%d", &n);

printf("Enter elements: ");


for (int i = 0; i < n; i++) {
scanf("%d", &value);
head = insertEnd(head, value);
}

printForward(head);
printBackward(head);

return 0;
}
4. Sparse Polynomial using Linked List(Optional):
You are required to implement a sparse polynomial using a linked list representation, where each node represents a term
in the form c · xp (coefficient times x raised to an exponent). The polynomial terms should always be stored in descending
order of exponents.
Implement the following functions:

1. addTerm(int coeff, int exp, Polynomial poly): Adds a term with coefficient coeff and exponent
exp to the existing polynomial poly. You may assume that no term with the same exponent already exists in the
polynomial. Insert the term such that the polynomial remains in decreasing order of exponents.
2. addPoly(Polynomial poly1, Polynomial poly2): Takes two polynomials poly1 and poly2, and
returns a new polynomial which is the sum of both. The original polynomials must remain unchanged. Assume both
input polynomials are sorted in descending order of exponents.
3. printPoly(Polynomial poly): Prints the polynomial in a readable format: c1xˆp1 + c2xˆp2 + ...
+ cnxˆpn.

Note: Use a linked list node structure such as:

typedef struct node {


int coeff;
int exp;
struct node* next;
} Node;

typedef Node* Polynomial;

Main Function:

int main() {
Polynomial poly1 = NULL, poly2 = NULL;

poly1 = makeTerm(1, 0, poly1);


poly1 = makeTerm(2, 2, poly1);
poly1 = makeTerm(4, 3, poly1);

poly2 = makeTerm(5, 0, poly2);


poly2 = makeTerm(1, 1, poly2);
poly2 = makeTerm(6, 3, poly2);
poly2 = makeTerm(3, 5, poly2);

printf("Polynomial 1 : ");
printPoly(poly1);

printf("Polynomial 2 : ");
printPoly(poly2);

Polynomial result = addPoly(poly1, poly2);


printf("Result Polynomial : ");
printPoly(result);

return 0;
}
Example:
Output:
Polynomial 1 : 4Xˆ3 + 2Xˆ2 + 1
Polynomial 2 : 3Xˆ5 + 6Xˆ3 + X + 5
Result Polynomial : 3Xˆ5 + 10Xˆ3 + 2Xˆ2 + X + 6

#include <stdio.h>
#include <stdlib.h>
struct polyTerm{
int coef;
int exp;
struct polyTerm *next;
};
typedef struct polyTerm *Polynomial;
void printPoly(Polynomial poly){Polynomial cur = poly;
while(cur!=NULL){
if(cur->exp==0){
printf("%d",cur->coef);
}
else{
if(cur->coef!=1){
printf("%d",cur->coef);
}
if(cur->exp!=0){
printf("X");
}
if(cur->exp!=1 && cur->exp!=0){
printf("ˆ%d",cur->exp);
}
}
cur = cur->next;
if(cur!=NULL){
printf("+");
}
}
printf("\n");
}
Polynomial makeTerm(int coef,int exp,Polynomial givenTerm){
Polynomial newTerm = (Polynomial)malloc(sizeof(struct polyTerm));
newTerm->coef = coef;
newTerm->exp = exp;
newTerm->next = givenTerm;
return newTerm;
}
Polynomial addTerm(int coef,int exp,Polynomial givenTerm){
Polynomial prev=NULL;
Polynomial curr = givenTerm;
while(curr!=NULL && curr->exp > exp){
prev = curr;
curr = curr->next;
}
if(prev == NULL){givenTerm = makeTerm(coef,exp,givenTerm);
}
else{
Polynomial newTerm = (Polynomial)malloc(sizeof(struct polyTerm));
newTerm->coef = coef;
newTerm->exp = exp;
prev->next = newTerm;
newTerm->next = curr;
}
return givenTerm;
}
Polynomial reverse(Polynomial poly){
Polynomial prev = NULL;
Polynomial cur = poly;
Polynomial curNext=NULL;
while(cur!=NULL){
curNext = cur->next;
cur->next = prev;
prev = cur;
cur=curNext;
}
return prev;
}
Polynomial addPoly(Polynomial poly1,Polynomial poly2){
Polynomial result=NULL;
Polynomial cur1=poly1,cur2=poly2;
while(cur1!=NULL && cur2!=NULL){
if(cur1->exp > cur2->exp){
result = makeTerm(cur1->coef,cur1->exp,result);
// printPoly(result);
cur1 = cur1->next;
}
else if(cur1->exp < cur2->exp){
result = makeTerm(cur2->coef,cur2->exp,result);
cur2 = cur2->next;
}
else{
result = makeTerm(cur1->coef+cur2->coef,cur1->exp,result);cur1 = cur1->next;
cur2 = cur2->next;
}
}
while(cur1!=NULL){
makeTerm(cur1->coef,cur1->exp,result);
cur1 = cur1->next;
}
while(cur2!=NULL){
makeTerm(cur2->coef,cur2->exp,result);
cur2 = cur2->next;
}
result = reverse(result);
return result;
}
int main(){
Polynomial poly1=NULL,poly2=NULL;
poly1 = makeTerm(1,0,poly1);
poly1 = makeTerm(2,2,poly1);
poly1 = makeTerm(4,3,poly1);
poly2 = makeTerm(5,0,poly2);
poly2 = makeTerm(1,1,poly2);
poly2 = makeTerm(6,3,poly2);
poly2 = makeTerm(3,5,poly2);
printf("Polynomial 1 : ");
printPoly(poly1);
printf("Polynomial 2 : ");
printPoly(poly2);
printf("Polynomial 2 After Adding New Term : ");
poly2 = addTerm(3,2,poly2);
printPoly(poly2);
Polynomial result = addPoly(poly1,poly2);
printf("Result Polynomial : ");
printPoly(result);
return 0;
}

You might also like