Assignment DS PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 45

1] arr[] = { 1,2,3,4,5}

#include <iostream>

using namespace std;

struct Node {

int data;

Node* next;

};

void insert(Node** root, int item)

Node* temp = new Node;

Node* ptr;

temp->data = item;

temp->next = NULL;

if (*root == NULL)

*root = temp;

else {

ptr = *root;

while (ptr->next != NULL)

ptr = ptr->next;

ptr->next = temp;

}
}

void display(Node* root)

while (root != NULL) {

cout << root->data << " ";

root = root->next;

Node *arrayToList(int arr[], int n)

Node *root = NULL;

for (int i = 0; i < n; i++)

insert(&root, arr[i]);

return root;

// Driver code

int main()

int arr[] = { 1, 2, 3, 4, 5 };

int n = sizeof(arr) / sizeof(arr[0]);

Node* root = arrayToList(arr, n);

display(root);

return 0;

}
3)
list1 = 5->2->3->8
list2 = 1->7->4->5
#include <iostream>

using namespace std;

// Representation of node

struct Node {

int data;

Node* next;

};

// Function to insert node in a linked list

void insert(Node** root, int item)

Node *ptr, *temp;

temp = new Node;

temp->data = item;

temp->next = NULL;

if (*root == NULL)

*root = temp;

else {

ptr = *root;

while (ptr->next != NULL)

ptr = ptr->next;

ptr->next = temp;
}

// Function which returns new linked list

Node* newList(Node* root1, Node* root2)

Node *ptr1 = root1, *ptr2 = root2, *ptr;

Node *root = NULL, *temp;

while (ptr1 != NULL) {

temp = new Node;

temp->next = NULL;

// Compare for greater node

if (ptr1->data < ptr2->data)

temp->data = ptr2->data;

else

temp->data = ptr1->data;

if (root == NULL)

root = temp;

else {

ptr = root;

while (ptr->next != NULL)

ptr = ptr->next;

ptr->next = temp;

ptr1 = ptr1->next;
ptr2 = ptr2->next;

return root;

void display(Node* root)

while (root != NULL) {

cout << root->data << "->";

root = root->next;

cout << endl;

// Driver code

int main()

Node *root1 = NULL, *root2 = NULL, *root = NULL;

// First linked list

insert(&root1, 5);

insert(&root1, 2);

insert(&root1, 3);

insert(&root1, 8);

cout << "First List: ";

display(root1);
// Second linked list

insert(&root2, 1);

insert(&root2, 7);

insert(&root2, 4);

insert(&root2, 5);

cout << "Second List: ";

display(root2);

root = newList(root1, root2);

cout << "New List: ";

display(root);

return 0;

4)

// Program for converting singly linked list

// into circular linked list.

#include <bits/stdc++.h>

/* Linked list node */

struct Node {

int data;

struct Node* next;

};

// Function that convert singly linked list

// into circular linked list.


struct Node* circular(struct Node* head)

// declare a node variable start and

// assign head node into start node.

struct Node* start = head;

// check that while head->next not equal

// to NULL then head points to next node.

while (head->next != NULL)

head = head->next;

// if head->next points to NULL then

// start assign to the head->next node.

head->next = start;

return start;

void push(struct Node** head, int data)

// Allocate dynamic memory for newNode.

struct Node* newNode = (struct Node*)malloc

(sizeof(struct Node));

// Assign the data into newNode.

newNode->data = data;

// newNode->next assign the address of

// head node.

newNode->next = (*head);
// newNode become the headNode.

(*head) = newNode;

// Function that display the elements of

// circular linked list.

void displayList(struct Node* node)

struct Node* start = node;

while (node->next != start) {

printf("%d ", node->data);

node = node->next;

// Display the last node of circular

// linked list.

printf("%d ", node->data);

// Driver program to test the functions

int main()

// Start with empty list

struct Node* head = NULL;

// Using push() function to construct

// singly linked list


// 17->22->13->14->15

push(&head, 15);

push(&head, 14);

push(&head, 13);

push(&head, 22);

push(&head, 17);

// Call the circular_list function that

// convert singly linked list to circular

// linked list.

circular(head);

printf("Display list: \n");

displayList(head);

return 0;

5)

// C++ program to merge a linked list into another at

// alternate positions

#include <bits/stdc++.h>

using namespace std;

// A nexted list node

class Node

public:

int data;
Node *next;

};

/* Function to insert a node at the beginning */

void push(Node ** head_ref, int new_data)

Node* new_node = new Node();

new_node->data = new_data;

new_node->next = (*head_ref);

(*head_ref) = new_node;

/* Utility function to print a singly linked list */

void printList(Node *head)

Node *temp = head;

while (temp != NULL)

cout<<temp->data<<" ";

temp = temp->next;

cout<<endl;

// Main function that inserts nodes of linked list q into p at

// alternate positions. Since head of first list never changes

// and head of second list may change, we need single pointer

// for first list and double pointer for second list.

void merge(Node *p, Node **q)


{

Node *p_curr = p, *q_curr = *q;

Node *p_next, *q_next;

// While therre are avialable positions in p

while (p_curr != NULL && q_curr != NULL)

// Save next pointers

p_next = p_curr->next;

q_next = q_curr->next;

// Make q_curr as next of p_curr

q_curr->next = p_next; // Change next pointer of q_curr

p_curr->next = q_curr; // Change next pointer of p_curr

// Update current pointers for next iteration

p_curr = p_next;

q_curr = q_next;

*q = q_curr; // Update head pointer of second list

// Driver code

int main()

Node *p = NULL, *q = NULL;

push(&p, 3);

push(&p, 2);
push(&p, 1);

cout<<"First Linked List:\n";

printList(p);

push(&q, 8);

push(&q, 7);

push(&q, 6);

push(&q, 5);

push(&q, 4);

cout<<"Second Linked List:\n";

printList(q);

merge(p, &q);

cout<<"Modified First Linked List:\n";

printList(p);

cout<<"Modified Second Linked List:\n";

printList(q);

return 0;

6)

// C++ program to Convert a String

// to a Singly Linked List

#include <iostream>

using namespace std;


// Structure for a Singly Linked List

struct node {

char data;

node* next;

};

// Function to add a new node to the Linked List

node* add(char data)

node* newnode = new node;

newnode->data = data;

newnode->next = NULL;

return newnode;

// Function to convert the string to Linked List.

node* string_to_SLL(string text, node* head)

head = add(text[0]);

node* curr = head;

// curr pointer points to the current node

// where the insertion should take place

for (int i = 1; i < text.size(); i++) {

curr->next = add(text[i]);

curr = curr->next;

return head;
}

// Function to print the data present in all the nodes

void print(node* head)

node* curr = head;

while (curr != NULL) {

cout << curr->data << " -> ";

curr = curr->next;

// Driver code

int main()

string text = "GEEKS";

node* head = NULL;

head = string_to_SLL(text, head);

print(head);

return 0;

7) List = 15 -> 16 -> 6 -> 7 -> 17

// C++ implementation to find minimum

// and maximum prime number of


// the singly linked list

#include <bits/stdc++.h>

using namespace std;

// Node of the singly linked list

struct Node {

int data;

Node* next;

};

// Function to insert a node at the beginning

// of the singly Linked List

void push(Node** head_ref, int new_data)

Node* new_node = new Node;

new_node->data = new_data;

new_node->next = (*head_ref);

(*head_ref) = new_node;

// Function to check if a number is prime

bool isPrime(int n)

// Corner cases

if (n <= 1)

return false;

if (n <= 3)

return true;
// This is checked so that we can skip

// middle five numbers in below loop

if (n % 2 == 0 || n % 3 == 0)

return false;

for (int i = 5; i * i <= n; i = i + 6)

if (n % i == 0 || n % (i + 2) == 0)

return false;

return true;

// Function to find maximum and minimum

// prime nodes in a linked list

void minmaxPrimeNodes(Node** head_ref)

int minimum = INT_MAX;

int maximum = INT_MIN;

Node* ptr = *head_ref;

while (ptr != NULL) {

// If current node is prime

if (isPrime(ptr->data)) {

// Update minimum

minimum = min(minimum, ptr->data);

// Update maximum

maximum = max(maximum, ptr->data);


}

ptr = ptr->next;

cout << "Minimum : " << minimum << endl;

cout << "Maximum : " << maximum << endl;

// Driver program

int main()

// start with the empty list

Node* head = NULL;

// create the linked list

// 15 -> 16 -> 7 -> 6 -> 17

push(&head, 17);

push(&head, 7);

push(&head, 6);

push(&head, 16);

push(&head, 15);

minmaxPrimeNodes(&head);

return 0;

9)

/* Program to insert in a sorted list */


#include <bits/stdc++.h>

using namespace std;

/* Link list node */

class Node

public:

int data;

Node* next;

};

/* function to insert a new_node in a list. Note that this

function expects a pointer to head_ref as this can modify the

head of the input linked list (similar to push())*/

void sortedInsert(Node** head_ref, Node* new_node)

Node* current;

/* Special case for the head end */

if (*head_ref == NULL || (*head_ref)->data >= new_node->data)

new_node->next = *head_ref;

*head_ref = new_node;

else

/* Locate the node before the point of insertion */

current = *head_ref;

while (current->next!=NULL &&

current->next->data < new_node->data)


{

current = current->next;

new_node->next = current->next;

current->next = new_node;

/* BELOW FUNCTIONS ARE JUST UTILITY TO TEST sortedInsert */

/* A utility function to create a new node */

Node *newNode(int new_data)

/* allocate node */

Node* new_node =new Node();

/* put in the data */

new_node->data = new_data;

new_node->next = NULL;

return new_node;

/* Function to print linked list */

void printList(Node *head)

Node *temp = head;

while(temp != NULL)

{
cout<<temp->data<<" ";

temp = temp->next;

/* Driver program to test count function*/

int main()

/* Start with the empty list */

Node* head = NULL;

Node *new_node = newNode(5);

sortedInsert(&head, new_node);

new_node = newNode(10);

sortedInsert(&head, new_node);

new_node = newNode(7);

sortedInsert(&head, new_node);

new_node = newNode(3);

sortedInsert(&head, new_node);

new_node = newNode(1);

sortedInsert(&head, new_node);

new_node = newNode(9);

sortedInsert(&head, new_node);

cout<<"Created Linked List\n";

printList(head);

return 0;

}
10)

// Iterative C++ program to reverse

// a linked list

#include <iostream>

using namespace std;

/* Link list node */

struct Node {

int data;

struct Node* next;

Node(int data)

this->data = data;

next = NULL;

};

struct LinkedList {

Node* head;

LinkedList()

head = NULL;

/* Function to reverse the linked list */

void reverse()

// Initialize current, previous and

// next pointers
Node* current = head;

Node *prev = NULL, *next = NULL;

while (current != NULL) {

// Store next

next = current->next;

// Reverse current node's pointer

current->next = prev;

// Move pointers one position ahead.

prev = current;

current = next;

head = prev;

/* Function to print linked list */

void print()

struct Node* temp = head;

while (temp != NULL) {

cout << temp->data << " ";

temp = temp->next;

void push(int data)

{
Node* temp = new Node(data);

temp->next = head;

head = temp;

};

/* Driver program to test above function*/

int main()

/* Start with the empty list */

LinkedList ll;

ll.push(20);

ll.push(4);

ll.push(15);

ll.push(85);

cout << "Given linked list\n";

ll.print();

ll.reverse();

cout << "\nReversed Linked list \n";

ll.print();

return 0;

11)

/* C++ program to merge two sorted linked lists */


#include <bits/stdc++.h>

using namespace std;

/* Link list node */

class Node

public:

int data;

Node* next;

};

/* pull off the front node of

the source and put it in dest */

void MoveNode(Node** destRef, Node** sourceRef);

/* Takes two lists sorted in increasing

order, and splices their nodes together

to make one big sorted list which

is returned. */

Node* SortedMerge(Node* a, Node* b)

/* a dummy first node to hang the result on */

Node dummy;

/* tail points to the last result node */

Node* tail = &dummy;

/* so tail->next is the place to

add new nodes to the result. */


dummy.next = NULL;

while (1)

if (a == NULL)

/* if either list runs out, use the

other list */

tail->next = b;

break;

else if (b == NULL)

tail->next = a;

break;

if (a->data <= b->data)

MoveNode(&(tail->next), &a);

else

MoveNode(&(tail->next), &b);

tail = tail->next;

return(dummy.next);

/* UTILITY FUNCTIONS */

/* MoveNode() function takes the

node from the front of the source,

and move it to the front of the dest.


It is an error to call this with the

source list empty.

Before calling MoveNode():

source == {1, 2, 3}

dest == {1, 2, 3}

Affter calling MoveNode():

source == {2, 3}

dest == {1, 1, 2, 3} */

void MoveNode(Node** destRef, Node** sourceRef)

/* the front source node */

Node* newNode = *sourceRef;

assert(newNode != NULL);

/* Advance the source pointer */

*sourceRef = newNode->next;

/* Link the old dest off the new node */

newNode->next = *destRef;

/* Move dest to point to the new node */

*destRef = newNode;

/* Function to insert a node at

the beginging of the linked list */


void push(Node** head_ref, int new_data)

/* allocate node */

Node* new_node = new Node();

/* put in the data */

new_node->data = new_data;

/* link the old list off the new node */

new_node->next = (*head_ref);

/* move the head to point to the new node */

(*head_ref) = new_node;

/* Function to print nodes in a given linked list */

void printList(Node *node)

while (node!=NULL)

cout<<node->data<<" ";

node = node->next;

/* Driver code*/

int main()

/* Start with the empty list */


Node* res = NULL;

Node* a = NULL;

Node* b = NULL;

/* Let us create two sorted linked lists

to test the functions

Created lists, a: 5->10->15, b: 2->3->20 */

push(&a, 15);

push(&a, 10);

push(&a, 5);

push(&b, 20);

push(&b, 3);

push(&b, 2);

/* Remove duplicates from linked list */

res = SortedMerge(a, b);

cout << "Merged Linked List is: \n";

printList(res);

return 0;

12)

// C++ program to sort Linked List

// using Bubble Sort

// by swapping nodes
#include <iostream>

using namespace std;

/* structure for a node */

struct Node

int data;

struct Node* next;

} Node;

/*Function to swap the nodes */

struct Node* swap(struct Node* ptr1, struct Node* ptr2)

struct Node* tmp = ptr2->next;

ptr2->next = ptr1;

ptr1->next = tmp;

return ptr2;

/* Function to sort the list */

int bubbleSort(struct Node** head, int count)

struct Node** h;

int i, j, swapped;

for (i = 0; i <= count; i++)

h = head;
swapped = 0;

for (j = 0; j < count - i - 1; j++)

struct Node* p1 = *h;

struct Node* p2 = p1->next;

if (p1->data > p2->data)

/* update the link after swapping */

*h = swap(p1, p2);

swapped = 1;

h = &(*h)->next;

/* break if the loop ended without any swap */

if (swapped == 0)

break;

/* Function to print the list */

void printList(struct Node* n)

while (n != NULL)
{

cout << n->data << " -> ";

n = n->next;

cout << endl;

/* Function to insert a struct Node

at the beginning of a linked list */

void insertAtTheBegin(struct Node** start_ref, int data)

struct Node* ptr1

= (struct Node*)malloc(sizeof(struct Node));

ptr1->data = data;

ptr1->next = *start_ref;

*start_ref = ptr1;

// Driver Code

int main()

int arr[] = { 78, 20, 10, 32, 1, 5 };

int list_size, i;

/* start with empty linked list */

struct Node* start = NULL;

list_size = sizeof(arr) / sizeof(arr[0]);


/* Create linked list from the array arr[] */

for (i = 0; i < list_size; i++)

insertAtTheBegin(&start, arr[i]);

/* print list before sorting */

cout <<"Linked list before sorting\n";

printList(start);

/* sort the linked list */

bubbleSort(&start, list_size);

/* print list after sorting */

cout <<"Linked list after sorting\n";

printList(start);

return 0;

14)

//C++ program for insertion and

// deletion in Circular Queue

#include <bits/stdc++.h>

using namespace std;

// Structure of a Node

struct Node

int data;

struct Node* link;


};

struct Queue

struct Node *front, *rear;

};

// Function to create Circular queue

void enQueue(Queue *q, int value)

struct Node *temp = new Node;

temp->data = value;

if (q->front == NULL)

q->front = temp;

else

q->rear->link = temp;

q->rear = temp;

q->rear->link = q->front;

// Function to delete element from Circular Queue

int deQueue(Queue *q)

if (q->front == NULL)

printf ("Queue is empty");

return INT_MIN;

}
// If this is the last node to be deleted

int value; // Value to be dequeued

if (q->front == q->rear)

value = q->front->data;

free(q->front);

q->front = NULL;

q->rear = NULL;

else // There are more than one nodes

struct Node *temp = q->front;

value = temp->data;

q->front = q->front->link;

q->rear->link= q->front;

free(temp);

return value ;

// Function displaying the elements of Circular Queue

void displayQueue(struct Queue *q)

struct Node *temp = q->front;

printf("\nElements in Circular Queue are: ");

while (temp->link != q->front)

{
printf("%d ", temp->data);

temp = temp->link;

printf("%d", temp->data);

/* Driver of the program */

int main()

// Create a queue and initialize front and rear

Queue *q = new Queue;

q->front = q->rear = NULL;

// Inserting elements in Circular Queue

enQueue(q, 14);

enQueue(q, 22);

enQueue(q, 6);

// Display elements present in Circular Queue

displayQueue(q);

// Deleting elements from Circular Queue

printf("\nDeleted value = %d", deQueue(q));

printf("\nDeleted value = %d", deQueue(q));

// Remaining elements in Circular Queue

displayQueue(q);

enQueue(q, 9);
enQueue(q, 20);

displayQueue(q);

return 0;

16)

// Iterative C++ program to find length

// or count of nodes in a linked list

#include <bits/stdc++.h>

using namespace std;

/* Link list node */

class Node

public:

int data;

Node* next;

};

/* Given a reference (pointer to pointer) to the head

of a list and an int, push a new node on the front

of the list. */

void push(Node** head_ref, int new_data)

/* allocate node */

Node* new_node =new Node();

/* put in the data */


new_node->data = new_data;

/* link the old list off the new node */

new_node->next = (*head_ref);

/* move the head to point to the new node */

(*head_ref) = new_node;

/* Counts no. of nodes in linked list */

int getCount(Node* head)

int count = 0; // Initialize count

Node* current = head; // Initialize current

while (current != NULL)

count++;

current = current->next;

return count;

/* Driver program to test count function*/

int main()

/* Start with the empty list */

Node* head = NULL;

/* Use push() to construct below list


1->2->1->3->1 */

push(&head, 1);

push(&head, 3);

push(&head, 1);

push(&head, 2);

push(&head, 1);

/* Check the count function */

cout<<"count of nodes is "<< getCount(head);

return 0;

18)

// Recursive CPP program to recursively insert

// a node and recursively print the list.

#include <bits/stdc++.h>

using namespace std;

struct Node {

int data;

Node* next;

};

// Allocates a new node with given data

Node *newNode(int data)

Node *new_node = new Node;

new_node->data = data;

new_node->next = NULL;

return new_node;
}

// Function to insert a new node at the

// end of linked list using recursion.

Node* insertEnd(Node* head, int data)

// If linked list is empty, create a

// new node (Assuming newNode() allocates

// a new node with given data)

if (head == NULL)

return newNode(data);

// If we have not reached end, keep traversing

// recursively.

else

head->next = insertEnd(head->next, data);

return head;

void traverse(Node* head)

if (head == NULL)

return;

// If head is not NULL, print current node

// and recur for remaining list

cout << head->data << " ";

traverse(head->next);
}

// Driver code

int main()

Node* head = NULL;

head = insertEnd(head, 6);

head = insertEnd(head, 8);

head = insertEnd(head, 10);

head = insertEnd(head, 12);

head = insertEnd(head, 14);

traverse(head);

19)

// C++ implementation of the above approach

#include <bits/stdc++.h>

using namespace std;

// Node structure containing powerer

// and coefficient of variable

struct Node {

int coeff, power;

Node* next;

};

// Function add a new node at the end of list

Node* addnode(Node* start, int coeff, int power)

// Create a new node


Node* newnode = new Node;

newnode->coeff = coeff;

newnode->power = power;

newnode->next = NULL;

// If linked list is empty

if (start == NULL)

return newnode;

// If linked list has nodes

Node* ptr = start;

while (ptr->next != NULL)

ptr = ptr->next;

ptr->next = newnode;

return start;

// Functionn To Display The Linked list

void printList(struct Node* ptr)

while (ptr->next != NULL) {

cout << ptr->coeff << "x^" << ptr->power << " + ";

ptr = ptr->next;

cout << ptr->coeff << "\n";

}
// Function to add coefficients of

// two elements having same powerer

void removeDuplicates(Node* start)

Node *ptr1, *ptr2, *dup;

ptr1 = start;

/* Pick elements one by one */

while (ptr1 != NULL && ptr1->next != NULL) {

ptr2 = ptr1;

// Compare the picked element

// with rest of the elements

while (ptr2->next != NULL) {

// If powerer of two elements are same

if (ptr1->power == ptr2->next->power) {

// Add their coefficients and put it in 1st element

ptr1->coeff = ptr1->coeff + ptr2->next->coeff;

dup = ptr2->next;

ptr2->next = ptr2->next->next;

// remove the 2nd element

delete (dup);

else

ptr2 = ptr2->next;

}
ptr1 = ptr1->next;

// Function two Multiply two polynomial Numbers

Node* multiply(Node* poly1, Node* poly2,

Node* poly3)

// Create two pointer and store the

// address of 1st and 2nd polynomials

Node *ptr1, *ptr2;

ptr1 = poly1;

ptr2 = poly2;

while (ptr1 != NULL) {

while (ptr2 != NULL) {

int coeff, power;

// Multiply the coefficient of both

// polynomials and store it in coeff

coeff = ptr1->coeff * ptr2->coeff;

// Add the powerer of both polynomials

// and store it in power

power = ptr1->power + ptr2->power;

// Invoke addnode function to create

// a newnode by passing three parameters

poly3 = addnode(poly3, coeff, power);


// move the pointer of 2nd polynomial

// two get its next term

ptr2 = ptr2->next;

// Move the 2nd pointer to the

// starting point of 2nd polynomial

ptr2 = poly2;

// move the pointer of 1st polynomial

ptr1 = ptr1->next;

// this function will be invoke to add

// the coefficient of the elements

// having same powerer from the resultant linked list

removeDuplicates(poly3);

return poly3;

// Driver Code

int main()

Node *poly1 = NULL, *poly2 = NULL, *poly3 = NULL;

// Creation of 1st Polynomial: 3x^2 + 5x^1 + 6

poly1 = addnode(poly1, 3, 2);


poly1 = addnode(poly1, 5, 1);

poly1 = addnode(poly1, 6, 0);

// Creation of 2nd polynomial: 6x^1 + 8

poly2 = addnode(poly2, 6, 1);

poly2 = addnode(poly2, 8, 0);

// Displaying 1st polynomial

cout << "1st Polynomial:- ";

printList(poly1);

// Displaying 2nd polynomial

cout << "2nd Polynomial:- ";

printList(poly2);

// calling multiply function

poly3 = multiply(poly1, poly2, poly3);

// Displaying Resultant Polynomial

cout << "Resultant Polynomial:- ";

printList(poly3);

return 0;

You might also like