0% found this document useful (0 votes)
19 views11 pages

DS Jobayer 1st

The document provides an overview of linked lists, including singly, doubly, and circular linked lists, along with their structures and traversal methods. It also covers Huffman coding, a greedy algorithm for lossless data compression, detailing its implementation and node structure. Additionally, it discusses counting binary trees using Catalan numbers and provides functions for calculating the number of nodes in a binary tree.

Uploaded by

greenlouisa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views11 pages

DS Jobayer 1st

The document provides an overview of linked lists, including singly, doubly, and circular linked lists, along with their structures and traversal methods. It also covers Huffman coding, a greedy algorithm for lossless data compression, detailing its implementation and node structure. Additionally, it discusses counting binary trees using Catalan numbers and provides functions for calculating the number of nodes in a binary tree.

Uploaded by

greenlouisa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

1

Topic 01: Linked List and Types of Linked list:


01: Linked List: Linked List is a type of data structure used for storing collections of data. The data is stored in
nodes, each of which contains a data field and a reference to the next node in the sequence. Structurally, a
linked list is organized into a sequence or chain of nodes, hence the name.

Example: // 2. put in the data

// Given a reference (pointer to pointer) new node->data = new data;

// to the head of a list and an int,

// inserts a new node on the front of // 3. Make next of new node as head

// the list. new node->next = (*head_ref);

void push(Node** head_ref, int new_data)

{ // 4. Move the head to point to

// 1. allocate node // the new node

Node* new node = new Node (); (*head_ref) = new_node;

Type of link list: There are three types of linked list.

1. Singly Linked list.


2. Doubly Linked list.
3. Circular Linked list.

1. Singly Linked list: It is the simplest type of linked list in which every node contains some data and a pointer to the next
node of the same data type. The node contains a pointer to the next node means that the node stores the address of the
next node in the sequence. A single linked list allows the traversal of data only in one way.

Structure of the singly linked list:

// Node of a singly linked list

class Node {

public:

int data;

// Pointer to next node in linked list

Node* next;

};
2

Creation and Traversal of Singly Linked List: // Driver Code

int main()

// C++ program to illustrate creation {

// and traversal of Singly Linked List Node* head = NULL;

Node* second = NULL;

#include <bits/stdc++.h> Node* third = NULL;

using namespace std;

// Allocate 3 nodes in the heap

// Structure of Node head = new Node();

class Node { second = new Node();

public: third = new Node();

int data;

Node* next; // Assign data in first node

}; head->data = 1;

// Function to print the content of // Link first node with second

// linked list starting from the head->next = second;

// given node

void printList(Node* n) // Assign data to second node

{ second->data = 2;

second->next = third;

// Iterate till n reaches NULL

while (n != NULL) { // Assign data to third node

third->data = 3;

// Print the data third->next = NULL;

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

n = n->next; printList(head);

} return 0;

} }

Output

123
3

2. Doubly Linked list: A doubly linked list or a two-way linked list is a more complex type of linked list that contains a
pointer to the next as well as the previous node in sequence.

Structure of Doubly Linked List:

// Node of a doubly linked list

struct Node {

int data;

// Pointer to next node in DLL

struct Node* next;

// Pointer to the previous node in DLL

struct Node* prev;

};

Creation and Traversal of Doubly Linked List: // Function to push a new element in

// the Doubly Linked List

// C++ program to illustrate creation void push(Node** head_ref, int new_data)

// and traversal of Doubly Linked List {

#include <bits/stdc++.h> // Allocate node

using namespace std; Node* new_node = new Node();

// Doubly linked list node // Put in the data

class Node { new_node->data = new_data;

public:

int data; // Make next of new node as

Node* next; // head and previous as NULL

Node* prev; new_node->next = (*head_ref);

}; new_node->prev = NULL;
4

// Change prev of head node to // Print the data

// the new node cout << " " << last->data << " ";

if ((*head_ref) != NULL) last = last->prev;

(*head_ref)->prev = new_node; }

// Move the head to point to

// the new node // Driver Code

(*head_ref) = new_node; int main()

} {

// Start with the empty list

// Function to traverse the Doubly LL Node* head = NULL;

// in the forward & backward direction

void printList(Node* node) // Insert 6.

{ // So linked list becomes 6->NULL

Node* last; push(&head, 6);

cout << "\nTraversal in forward" // Insert 7 at the beginning. So

<< " direction \n"; // linked list becomes 7->6->NULL

while (node != NULL) { push(&head, 7);

// Print the data // Insert 1 at the beginning. So

cout << " " << node->data << " "; // linked list becomes 1->7->6->NULL

last = node; push(&head, 1);

node = node->next;

} cout << "Created DLL is: ";

printList(head);

cout << "\nTraversal in reverse"

<< " direction \n"; return 0;

while (last != NULL) { }

Output
Circular Linked List: A
Created circular
DLL is: linked list is that
in which the last node contains the pointer to the
Traversal
first node in forward
of the list. Below isdirection
the structure of the
Circular Linked List:
1 7 6

Traversal in reverse direction

6 7 1
5

Structure for a node:

class Node {

public:

int data;

// Pointer to next node in CLL

Node* next;

};

Creation and Traversal of Circular Linked List:

// C++ program to illustrate creation // set the next of last node

// and traversal of Circular LL if (*head_ref != NULL) {

while (temp->next != *head_ref) {

#include <bits/stdc++.h> temp = temp->next;

using namespace std; }

temp->next = ptr1;

// Structure for a node }

class Node {

public: // For the first node

int data; else

Node* next; ptr1->next = ptr1;

};
*head_ref = ptr1;

// Function to insert a node at the }

// beginning of Circular LL

void push(Node** head_ref, int data) // Function to print nodes in the

{ // Circular Linked List

Node* ptr1 = new Node(); void printList(Node* head)

Node* temp = *head_ref; {

ptr1->data = data; Node* temp = head;

ptr1->next = *head_ref; if (head != NULL) {

do {

// If linked list is not NULL then


6

// Print the data // be 11->2->56->12

cout << temp->data << " push(&head, 12);


";
push(&head, 56);
temp = temp->next;
push(&head, 2);
} while (temp != head);
push(&head, 11);
}

}
cout << "Contents of Circular"

<< " Linked List\n ";


// Driver Code

int main()
// Function call
{
printList(head);
// Initialize list as empty

Node* head = NULL;


return 0;

}
// Created linked list will

Output

Contents of Circular Linked List

11 2 56 12

Topic 02: Huffman Coding:


 Huffman Coding is a famous Greedy Algorithm.

 It is used for the lossless compression of data.

 It uses variable length encoding.

 It assigns variable length code to all the characters.

 The code length of a character depends on how frequently it occurs in the given text.

 The character which occurs most frequently gets the smallest code.

 The character which occurs least frequently gets the largest code.

 It is also known as Huffman Encoding.


7

Example:

#include<iostream> child1->traverse(code+'1');

#include<queue> //add 1 with the code as right child

#include<string> }else{

using namespace std; cout << "Data: " << data<< ",

struct node{ Frequency: "<<freq << ", Code: " <<

int freq; code<<endl;

char data; }

const node *child0, *child1; }

node(char d, int f = -1){ //assign };

values in the node void huffmanCoding(string str){

data = d; priority_queue<node> qu;

freq = f; int frequency[256];

child0 = NULL; for(int i = 0; i<256; i++)

child1 = NULL; frequency[i] = 0; //clear all

} frequency

node(const node *c0, const node *c1){ for(int i = 0; i<str.size(); i++){

data = 0; frequency[int(str[i])]++;

freq = c0->freq + c1->freq; //increase frequency

child0=c0; }

child1=c1; for(int i = 0; i<256; i++){

} if(frequency[i]){

bool operator<( const node &a ) const { qu.push(node(i,

//< operator performs to find priority frequency[i]));

in queue }

return freq >a.freq; }

} while(qu.size() >1){

void traverse(string code = "")const{ node *c0 = new node(qu.top());

if(child0!=NULL){ //get left child and remove from queue

child0->traverse(code+'0'); qu.pop();

//add 0 with the code as left child node *c1 = new node(qu.top());
8

//get right child and remove from queue }

qu.pop(); cout << "The Huffman Code: "<<endl;

qu.push(node(c0, c1)); //add freq qu.top().traverse(); //traverse the

of two child and add again in the queue

tree to get code

} //arbitray string to get frequency

main(){ huffmanCoding(str);

string str = "ACCEBFFFFAAXXBLKE"; }

1. Node Structure:
A node structure is defined to represent each node in the Huffman tree. Each node has information
about the character (data), frequency (freq), and pointers to its left and right children (child0 and
child1).

2. Huffman Coding Function (Huffman Coding):


• A function is created to perform Huffman coding on a given input string.
• The function initializes a priority queue to store nodes based on their frequencies.
• It counts the frequency of each character in the input string and creates leaf nodes for each
character with their corresponding frequencies.
• The leaf nodes are pushed into the priority queue.
• The function then builds the Huffman tree by combining nodes with the lowest frequencies until
only one node (the root of the tree) is left in the queue.
• Finally, it traverses the Huffman tree from the root and prints the Huffman codes for each
character.

3. Main Function (main):


• The main function is the entry point of the program.
• It creates an example string "BSFMSTU" to demonstrate Huffman coding.
• Calls the Huffman Coding function with the example string.
9

4. Node Constructors and Functions:

• Constructors for the node structure are defined. There's one constructor for leaf nodes, taking a
character and frequency, and another for internal nodes, combining two child nodes.
• The < operator is overloaded to define the priority of nodes in the priority queue based on their
frequencies.

Topic 03: Counting Binary Tree


Counting the number of binary trees with a given number of nodes is a well-known problem in combinatory.
The number of binary trees with n nodes is given by the nth Catalan number. The formula for the nth Catalan
number, denoted as Cn, is given by:

#include <iostream> int n;

using namespace std; cout << "Enter the number of

// Function to calculate the factorial of nodes: ";

a number cin >> n;

unsigned long long factorial(int n) { if (n < 0) {

if (n == 0 || n == 1) cout << "Invalid input. Number

return 1; of nodes should be non-negative." <<

return n * factorial(n - 1); endl;

} } else {

// Function to calculate the number of unsigned long long result =

binary trees with n nodes countBinaryTrees(n);

unsigned long long countBinaryTrees(int cout << "Number of binary

n) { trees with " << n << " nodes: " <<

return factorial(2 * n) / result << endl;

(factorial(n + 1) * factorial(n)); }

} return 0;

int main() { }
10

Explanation:
1. Factorial Function (factorial): This function calculates the factorial of a given number n. The base cases are
defined for n = 0 and n = 1, where the factorial is 1. For other values, it recursively calculates n * factorial(n - 1).
2. Count Binary Trees Function (countBinaryTrees):
• This function calculates the number of unique binary trees that can be formed with n nodes.
• It uses the Catalan number formula: Catalan(n) = (2n)! / ((n + 1)! * n!). The function calls the factorial function
to calculate the factorials needed for this formula.

3. Main Function (main):


• The main function is the starting point of the program.
• It prompts the user to enter the number of nodes (n) for which the number of binary trees will be calculated.
• Checks if the input is non-negative. If the input is negative, it prints an error message.
• If the input is valid, it calls the countBinaryTrees function to calculate the number of binary trees and prints the
result.

4. Output:
• The program outputs the number of binary trees that can be formed with the specified number of nodes.

Count number of nodes in a complete Binary Tree:


class node {
public:
int data;
node* left;
node* right;
};

• This defines a simple structure for a binary tree node, where each node has an integer data value
and pointers to its left and right children.

int totalNodes(node* root) {


if (root == NULL)
return 0;

int l = totalNodes(root->left);
int r = totalNodes(root->right);

return 1 + l + r;
}

• The totalNodes function takes the root of the tree as an argument.


• It checks if the root is NULL, in which case it returns 0, indicating an empty tree.
• It recursively calls itself for the left and right subtrees and adds the results.
• The function returns 1 + l + r, where l is the count of nodes in the left subtree, and r is the count of
nodes in the right subtree.
11

node* newNode(int data) {


node* Node = new node();
Node->data = data;
Node->left = NULL;
Node->right = NULL;
return (Node);

• The newNode function is a helper function that creates a new node with the given data value
int main()
{
node* roo t = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(9);
root->right->right = newNode(8);
root->left->left->left = newNode(6);

root->left->left->right = newNode(7);

cout << totalNodes(root);

return 0;

• In the main function, a binary tree is constructed using the newNode function to create nodes with
different data values.
• The totalNodes function is then called with the root of the tree, and the result (total number of
nodes) is printed to the console.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy