16
CHAPTER 4: LINKED LIST An ordered collection of data in which each element contains the location of the next element or elements using pointers. A size of a pointer can be changed when the data is a dynamic structure type. Each node contains two field: data link If the last pointer in the last node isn’t pointing to anything it is given the NULL (empty) value. Linked list structures usually save space, time, and programming effort. o The structures are large or need to hold large records. o The size of the list is not known in advance. o Flexibility is needed during insertions, deletions, and reordering of elements. When the allocated memory isn’t initialized, pointer is assigning the sufficient memory dynamically using malloc() function or new node. X = new int/new node Malloc() returns the address of the first byte in the memory space allocated/available. In one list, there are 3 main pointers: o Head – first node in list o Cur – current node o Prev – previous node before current 6 Basic Operation Linked List using Pointer Define a linked list structure called studentName (string), studentID (integer), CGPA (floating), and pointer to the next record in the structure which is called link. Solution 1 Solution 2 Student *first; Student *last; Student *newNode; first = NULL; newNode = new Student; Create list Create new node Insert new node Delete node Retrie ve Traver sal newNode las Stored Contains the address of the next struct Student { char studentName (20); int studentID; float CGPA; struct Student struct node { struct Student Info; struct Student *link; struct Student { char studentName (20); int studentID; float CGPA; struct Student name ID fir newNode las fir name ID xxx xxx xxx

Midsem Note

Embed Size (px)

DESCRIPTION

data structure brief notes

Citation preview

Page 1: Midsem Note

CHAPTER 4: LINKED LIST◌ An ordered collection of data in which

each element contains the location of the next element or elements using pointers.

◌ A size of a pointer can be changed when the data is a dynamic structure type.

◌ Each node contains two field:data link

◌ If the last pointer in the last node isn’t pointing to anything it is given the NULL (empty) value.

◌ Linked list structures usually save space, time, and programming effort.

o The structures are large or need to hold large records.

o The size of the list is not known in advance.

o Flexibility is needed during insertions, deletions, and reordering of elements.

◌ When the allocated memory isn’t initialized, pointer is assigning the sufficient memory dynamically using malloc() function or new node.

X = new int/new node◌ Malloc() returns the address of the first

byte in the memory space allocated/available.◌ In one list, there are 3 main pointers:

o Head – first node in listo Cur – current nodeo Prev – previous node before

current◌ 6 Basic Operation

Linked List using Pointer Define a linked list structure called studentName (string), studentID (integer), CGPA (floating), and pointer to the next record in the structure which is called link.

Solution 1

Solution 2

Student *first;Student *last;Student

*newNode;

first = NULL;

newNode = new Student;

Create list

Create new node

Insert new node

Delete node

Retrieve

Traversal

newNode

current

newNode

newNodelast

Stored data item

Contains the address of the next element in the list

struct Student {char studentName (20);int studentID;float CGPA;

struct node {struct Student Info;struct Student *link;

};

struct Student {char studentName (20);int studentID;float CGPA;

struct Student *link;};

name ID CGPA link

first

newNodelastfirst

name ID CGPA linkxxx xxx xxx

name ID CGPA linkxxx xxx xxx

lastfirst

name ID CGPA linkxxx xxx xxx

name ID CGPA linkxxx xxx xxx

first = newNode;last =

last

last

current

newNode = new Student;last -> link = cout << “Enter Student Name”;cin.getline(newNode->name, 20);cout << “Enter Student ID”;cin >> newNode >> studentID);cout << “Enter Student’s CGPA”;cin >> newNode >> CGPA;newNode -> link = NULL;

last = newNode;newNode = new Student;

Student *current;current = first;current = current -> link; //until the end of node = NULL

Page 2: Midsem Note

Infix Postfixa + b a b +

a + b * c a b c * +a * b + c a b * c +

(a + b) * c a b + c *(a – b) * (c + d) a b – c d + *

(a + b) * (c – d / e) + f

a b + c d e / - * f +

MAIN ALGORITHMPursuant to the previous discussion, the main algorithm in pseudocode is as follow:

Read the first character while not the end of input data

{a. Initialize the stackb. Process the expressionc. Output resultd. Get the next expression

}

ALGORITHM IN STACK (PUSH POP CREATE STACKTOP)A stack is a linear list in which all additions and deletions are restricted to one end, called the top.

Data input as {5, 10, 15, 20} is removed as [20, 15, 10, 5}. This reversing attribute is why stacks are known as the last in – first out (LIFO) data structure.

BASIC STACK OPERATIONS

PUSHPush adds an item at the top of the stack. After the push, the new item becomes the top; if there is enough room. If not, the stack is in an overflow state.

PUSHPop removes an item at the top of the stack and return it to the user. After the push, the next old item becomes the top; if there is enough room. If not, the stack is in an underflow state.

struct Student {char studentName (20);int studentID;float CGPA;

Page 3: Midsem Note

STACK TOPStack top copies the item at the top of the stack; that is, it returns the data in the top element to the user but does not delete it. Stack top can also result in underflow if the stack is empty.

//Basic stack operation

//Stack Linked List implementation

Data StructureTo implement the linked list stack, we need two different structures, a head and a data node. The head structure contains metadata – that is data about data and pointer to the top of the stack.

The data structure contains data and a link pointer to the next node in the stack.

Stack HeadGenerally, the head for a stack requires only two attributes: a top pointer and count of the number elements in the stack. Allow the user to determine the average number of items processed through the stack in a given period.

Stack Data NodeThe data structure is a typical linked list data node.

Stack Algorithm //Create Stack

Page 4: Midsem Note

//Push Stack

//Pop StackPop stack sends the data in the node at the top of the stack back to the calling algorithm. It then adjusts the pointers to logically delete the node. After the node has been logically deleted, it is physically deleted by recycling the memory that is returning it to dynamic memory. After the count is adjusted by subtracting 1, the algorithm returns the status to the caller: if the pop was successful, it returns true; if the stack is empty when pop is called, it returns false.

//Stack TopSends the data at the top of the stack back to the calling module without deleting the top node.

//Empty StackEmpty stack is provided to implement the structured programming concept of data hiding. If the entire program has access to the stack head structure, it is not needed. However, if the stack is implemented as a separately compiled program to be linked with other programs, the calling program may not have access to the stack head node.

//Full Stack

//Simple Stack Application Program

Page 5: Midsem Note

#include <iostream>

using namespace std;

struct node {int data;node *top;node *link;

public:

node() {top = NULL;link = NULL;

}

void push(int x) { node *n = new node;n -> data = x;n -> link = top;top = n;cout << "\nThe List is: ";

n++;}

void pop() {node *n = new node;n = top;top = top -> link;n -> link = NULL;cout << "The List is: ";delete n;

}

void print() {node *n = new node;n = top;

while(n!=NULL) {cout << n -> data << " ";n = n -> link;

}

delete n;}

void printz() {node *n = new node;n = top;while(n!=NULL) {

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

}

delete n;}

};

int main() {

cout << "Processing An Integer Stack" << endl;

node stack;stack.push(0);stack.print();stack.push(1);stack.print();stack.push(2);stack.print();

cout << endl;

cout << "\n2 Popped From Stack" << endl;stack.pop();stack.printz();

cout << endl;

cout << "\n1 Popped From Stack" << endl;stack.pop();stack.printz();

cout << endl;cout << endl;

cout << "\No Popped From Stack" << endl;cout << "The List is Empty";

cout << endl;cout << endl;

system("pause");

}

Page 6: Midsem Note

#include <iostream>

using namespace std;

class node {double data;node *top;node *link;

public:node() {

top = NULL;link = NULL;

}

void push(double x) {node *n = new node;n -> data = x;n -> link = top;top = n;

}

void pop() {node *n = new node;n = top;top = top -> link;n -> link = NULL;

delete n;}

void print() {node *n = new node;n = top;

while(n!=NULL) {cout << n -> data <<

endl;n = n -> link;

}

delete n;}

};

int main() {cout << "Stack is Empty" << endl;

cout << endl;

cout << "Elements That are Pushed into Stack: " << endl;

node stack;stack.push(999.9);stack.push(10);stack.push(26);stack.push(40.6);stack.push(23.6);stack.print();

cout << endl;

cout << "Elements That are Popped Out of Stack: " << endl;

stack.pop();stack.pop();stack.pop();stack.print();

cout << endl;

cout << "Elements That are Copied: " << endl;

stack.print();

cout << endl;

system("pause");}

Page 7: Midsem Note

CHAPTER 6: QUEUEA queue is a linear list in which data can only be inserted at one end, called the rear and deleted from the other end, called the front. These restrictions ensure that the data are processed through the queue in the order in which they are received. In other words, a queue is a first in – first out (FIFO) structure.

A queue is the same as a line. For example, a line of people waiting for the bus at a bus station, a list of calls put on hold to be answered by telephone operator and a list of waiting jobs to be processed by a computer.

In queue structure, data can be inserted at the rear, deleted from the front, retrieved from the front and retrieved from the rear.

The difference between stack and queue is that the queue implementation needs to keep track of the front and the rear of the queue, whereas the stack only needs to worry about one end: the top.

FOUR(4) Basic Queue Operation

EnqueueThe queue inserted operation. After

the data have been inserted into the queue, the new element becomes the rear. The only potential problem with enqueue is running out of room for the data. If there is not enough room for another element in the queue, the queue is in an overflow state.

Dequeue

The queue deleted operation. The data at the front of the queue are returned to the user and removed from the queue. If there are no data in the queue when a dequeue is attempted, the queue is in an underflow state.

Queue FrontData at the front of the queue can be

retrieved with queue front. It returns the data at the front of the queue without changing the contents of the queue. If there are no data in the queue when a queue front is attempted, then the queue is in an underflow state.

Queue RearA parallel operation to queue front

retrieves the data at the rear of the queue. If there are no data in the queue when a queue rear is attempted, the queue is in an underflow state.

A queue is a linear list in which data can be inserted at one end, called the rear and deleted from the other end called the front. It is a first in – first out (FIFO) restricted data structure.

Page 8: Midsem Note
Page 9: Midsem Note

//Queue Linked List Design

Queue HeadThe queue requires two pointers and a count. These fields are stored in the queue head structure. Other queue attributes, such as the maximum number of items that were ever present in the queue and the total number of items that have been processed through the queue, can be stored in the head node if such data are relevant to an application.

Queue Data NodeThe queue data node contains the user data and a link field pointing to the next node, if any. These nodes are stored in dynamic memory and are inserted and deleted as requested by the using program.

//Queue Algorithms

Create QueueTo create queue, what we have to do is to set the metadata pointers to null and the count to 0. The algorithm is shown below.

Page 10: Midsem Note

◌ Queue is a first-in, first-out (FIFO) data structure. i.e. the element added first to the queue will be the one to be removed first.

◌ Elements are always added to the back of the queue and removed from the front of the queue.

◌ Typical use cases of queues include: (1) In Inter-Process Communication (IPC) message queues is a common mechanism for communication between processes.

◌ Some of the common terminology associated with queues inlcude ADD/ PUSH and DELETE/ POP of elements to the queue.

◌ ADD/ PUSH refers to adding an element to the queue.

◌ DELETE/ POP refers to removing an element from the queue.

◌ A queue is a list from which items may be deleted at one end (front) and into which items may be inserted at the other end (rear)

◌ Similar to checkout line in a grocery store - first come first served.

Queues have many applications in computer systems:

1. Jobs in a single processor computer

2. Print spooling3. Information packets in computer

networks

//Primitive operations

1) Enqueuer (q, x): inserts item x at the rear of the queue q.

2) x = dequeuer (q): removes the front element from q and returns its value.

3) isEmpty(q): true if the queue is empty, otherwise false.

//Example

Enqueue (q, ‘A’);Enqueue (q, ‘B’);Enqueue (q, ‘C’);x = dequeuer (q);Enqueue (q, ‘D’);Enqueue (q, ‘E’);

A B C

x = dequeuer (q) -> x = ‘A’

B C D E

rearfronrearfron

rearfron

Page 11: Midsem Note

#include <iostream>#include <iomanip>

using namespace std;

struct node {double data;node *link;

};

class queue_linkedList {

private:node *top = NULL;int counter = 0;node *rear = NULL;

public:void enqueue(double x) {

node *n = new node;n -> data = x;n -> link = NULL;

if (top == NULL)top = rear = n;

else {rear -> link = n;rear = n;}

counter++;}

void dequeue() {

if (top == NULL)cout << "The List is Empty" << endl;

else {double element = top -> data;node *tmp = top;tmp = top;delete tmp;

cout << element << " " << "Dequeued" << endl;}

counter--;}

void printQueue() {

if (top == NULL)cout << "The List is Empty" << endl;

else {node *y = new node;y = top;

cout << "The List is: ";

while (y != NULL) {cout << y -> data << " ";y = y -> link;

}}

cout << endl << endl;}

};

int main() {

cout << "Processing A Double Queue" << endl;cout << endl;

class queue_linkedList saff;

saff.enqueue(1.1);saff.printQueue();saff.enqueue(2.2);saff.printQueue();saff.enqueue(3.3);saff.printQueue();saff.enqueue(4.4);saff.printQueue();

saff.dequeue();saff.printQueue();saff.dequeue();saff.printQueue();saff.dequeue();saff.printQueue();

system("pause");}

Page 12: Midsem Note

#include <iostream>

using namespace std;

const int SIZE = 4;

struct node {int data;node *link;

};

class intQueue {

private:node *top = NULL;int counter = 1;node *rear = NULL;

public:void enqueue(int x) {

if (counter > SIZE)cout << "Overflow" << endl;

else {node *n = new node;n -> data = x;n -> link = NULL;

if (top == NULL)top = rear = n;

else {rear -> link = n;rear = n;}

}

counter++;}

void dequeue() {if (counter < 1)cout << "Underflow" << endl;

else {double element = top -> data;node *tmp = top;tmp = top;top = top -> link;delete tmp;

}

counter--;}

void queueFront() {

if (top == NULL)cout << "The Queue is Empty" << endl;

elsecout << top -> data;

}

void queueRear() {

if (rear == NULL)cout << "The Queue is Empty" << endl;

elsecout << rear->data;

}

void printQueue() {if (top == NULL)

cout << "Empty" << endl;

else {node *y = new node;y = top;

cout << "intQueue Elements: ";

while (y != NULL) {cout << y -> data << " ";y = y -> link;

}}

cout << endl << endl;}

};

int main() {class intQueue piyot;

piyot.enqueue(300);piyot.enqueue(180);piyot.enqueue(500);piyot.enqueue(666);

cout << "The Front Element of intQueue :" << " ";

piyot.queueFront();

cout << endl << endl;

cout << "The Last Element of intQueue :" << " ";

piyot.queueRear();

cout << endl << endl;

piyot.dequeue();cout << "After The Pop Operation, The

Front Element of intQueue : ";piyot.queueFront();

cout << endl << endl;

piyot.printQueue();

system("pause");}