Docsity Assignment 1 Data Structure Algorithms Pass
Docsity Assignment 1 Data Structure Algorithms Pass
Unit number and title Unit 19: Data Structures and Algorithms
Student declaration
I certify that the assignment submission is entirely my own work and I fully understand the consequences of plagiarism. I understand
that making a false declaration is a form of malpractice.
P1 P2 P3 M1 M2 M3 D1 D2
IV Signature:
Chapter 1: Create a design specification for data structures explaining the valid operations
that can be carried out on the structures. (P1) ........................................................................................... 8
1. Definition. .................................................................................................................................................................8
2. Examples. ..................................................................................................................................................................8
Chapter 2: Determine the operations of a memory stack and how it is used to implement
function calls in a computer. (P2) ................................................................................................................. 32
Chapter 3: Using an imperative definition, specify the abstract data type for a software stack.
(P3)........................................................................................................................................................................... 37
Conclusion ............................................................................................................................................................. 55
References ............................................................................................................................................................. 56
Table of Tables
Table 1: Basic Operations. ....................................................................................................................................................9
Table 2: Example Queue in VDM. ................................................................................................................................... 25
Table 3: Example Stack in VDM. ..................................................................................................................................... 38
2. Examples.
A Doubly Linked List, as opposed to a Single Linked List, is a form of a Linked List in
which navigation is accessible in both ways, forward and backward. The following are
key words to grasp the notion of a doubly linked list.
Link – A linked list's links can each hold data known as elements.
Next – Each link in a linked list has a Next link to the next link.
Prev − Each link in a shared
Document linked list has a Prev link to the previous link.
on www.docsity.com
Downloaded by: thanhngan202 (vothithanhngann@gmail.com)
LinkedList − A Linked List has a connection link to the first link named First
and a connection link to the last link called Last.
Figure 2: Doubly Linked List Representation.
c) Set the prev pointer of new node and the next node.
assign the value of prev of next node to the prev of newNode
assign the address of newNode to the prev of next node
// if the linked list is not empty, traverse to the end of the linked list
while (temp.next != null)
temp = temp.next;
Finally, free the memory of del_node . And, the linked will look like this
If del_node is an inner node (second node), we must have to reset the value
of next and prev of the nodes before and after the del_node .
For the node before the del_node (i.e. first node)
Assign the value of next of del_node to the next of the first node.
For the node after the del_node (i.e. third node)
Assign the value of prev of del_node to the prev of the third node.
Finally, we will free the memory of del_node . And, the final doubly linked list looks
like this.
// if del_node is the head node, point the head pointer to the next of del_node
if (head == del_node) {
head = del_node.next;
}
// if del_node is not at the last node, point the prev of node next to del_node
// to the previous of del_node
if (del_node.next != null) {
del_node.next.prev = del_node.prev;
}
// if del_node is not the first node, point the next of the previous node to the
// next node of del_node
if (del_node.prev != null) {
del_node.prev.next = del_node.next;
}
// node creation
Node head;
class Node {
int data;
Node prev;
Node next;
Node(int d) {
data = d;
}
}
// if the linked list is not empty, traverse to the end of the linked list
while (temp.next != null)
temp = temp.next;
// assign next of the last node (temp) to newNode
temp.next = new_node;
// assign prev of newNode to temp
new_node.prev = temp;
}
// delete a node from the doubly linked list
void deleteNode(Node del_node) {
// if head or del is null, deletion is not possible
if (head == null || del_node == null) {
return;
}
// if del_node is the head node, point the head pointer to the next of
del_node
if (head == del_node) {
head = del_node.next;
}
// if del_node is not at the last node, point the prev of node next to
del_node
// to the previous of del_node
if (del_node.next != null) {
del_node.next.prev = del_node.prev;
}
// if del_node is not the first node, point the next of the previous node to
the
// next node of del_node
if (del_node.prev != null) {
del_node.prev.next = del_node.next;
}
}
// print the doubly linked list
public void printlist(Node node) {
Node last = null;
while (node != null) {
System.out.print(node.data + "->");
last = node;
node = node.next;
Document shared on www.docsity.com
} Downloaded by: thanhngan202 (vothithanhngann@gmail.com)
System.out.println();
}
public static void main(String[] args) {
DoublyLinkedList doubly_ll = new DoublyLinkedList();
doubly_ll.insertEnd(5);
doubly_ll.insertFront(1);
doubly_ll.insertFront(6);
doubly_ll.insertEnd(9);
Because queue is a dynamic set, it may insert and delete elements as well as perform
other actions. The Queue data structure is shown below.
Name: Queue
Symbol: Queue
Values: queue of nat1, queue of bool, queue of char, …
Document shared on www.docsity.com
Downloaded by: thanhngan202 (vothithanhngann@gmail.com)
Operator: Assume that a in the following denote arbitrary queues of which their data
types is an arbitrary type b
Operator Name Type
Enqueue a Enqueue Queue of b-> Queue of b
Dequeue a Dequeue Queue of b -> b
Peek a Peek Queue of b -> b
Size a Find size Queue of b -> nat1
IsEmpty a Find if a is empty Queue of b -> bool
IsFull a Find if full Queue of b -> bool
Table 2: Example Queue in VDM.
Dequeue().
Accessing data from the queue entails two steps: accessing the data where the front is
pointing and removing the data after access. To do a dequeue operation, take the
following steps:
Step 1 − Check if the queue is empty.
Step 2 − If the queue is empty, produce underflow error and exit.
Step 3 − If the queue is not empty, access the data where front is pointing.
Step 4 − Increment front pointer to point to the next available data element.
Step 5 − Return success.
System.exit(-1);
}
int x = arr[front];
count--;
return x;
}
Figure 32: Dequeue in Java.
Peek().
This function facilitates viewing the data at the front of the queue. The peek() function's
algorithm is as follows:
isFull().
This action produces a boolean result indicating whether or not the queue is full.
isEmpty().
This operation returns a boolean value that indicates whether or not the queue is
empty.
Size().
This operation returns the total number of elements present in the queue.
package Queue;
class Queue
{
private int[] arr; // array to store queue elements
private int front; // front points to the front element in the
queue
private int rear; // rear points to the last element in the
queue
private int capacity; // maximum capacity of the queue
private int count; // current size of the queue
return x;
}
When a function is invoked, a new stack frame is created and the steps listed below will
be carried out:
Step 1: Arguments are stored on the stack.
Step 2: Current frame pointer and return address are recorded.
Step 3: Local variables areonallocated
Document shared www.docsity.com memory.
Downloaded by: thanhngan202 (vothithanhngann@gmail.com)
The following is an example of a recursion function that uses the "Tower of Hanoi" issue and
how it acts in stack memory.
if (n == 1)
{
System.out.println("Move disk 1 from rod " + from_rod + " to rod " +
to_rod);
return;
}
towerOfHanoi(n-1, from_rod, aux_rod, to_rod);
System.out.println("Move disk " + n + " from rod " + from_rod + " to rod " +
to_rod);
towerOfHanoi(n-1, aux_rod, to_rod, from_rod);
}
public static void main(String[] args) {
Recursion recursion = new Recursion();
Scanner sc = new Scanner(System.in);
int n;
System.out.print("Enter number: ");
n = sc.nextInt();
System.out.println("Tower of Hanoi in "+n+" disk:");
recursion.towerOfHanoi(n, 'A', 'C', 'B');
}
Figure 42: Tower Of Hanoi code for recursion's example.
As we can see, the function began with a base case of 1 and a function call to itself. When the
number is n (the number of disk that you want to input), the function calls in the stack memory
will act as follows.
It’s a linear data structure of which the operations follow a particular order. “The order may
be LIFO(Last In First Out) or FILO(First In Last Out).” (GeeksforGeeks, 2022). Just like the real
world “stacks”, stack only allow users to do all the data operations on one end only.
}
Figure 49: Push in Java.
Pop()
Pop Operation refers to accessing the content while removing it from the stack. The data
element is not really destroyed in an array implementation of the pop() action; instead, top is
decremented to a lower place in the stack to refer to the next item. Pop(), on the other hand,
removes data elements and deal-locates memory space in linked-list implementations.
The following steps may be involved in a Pop operation:
Step 1: Determines whether or not the stack is empty.
Step 2: If the stack is empty, an error is generated and the program exits.
Step 3: If the stack is not empty, it accesses the data element pointed to by top.
Step 4: Lowers the value of top by one.
Step 5: Success is returned.
}
Figure 51: Pop in Java.
Peek()
This operation returns the top element of the stack without removing it.
return -1;
}
Figure 53: Peek in Java.
isFull()
The operation determines whether or not a stack is full and then returns a Boolean value. If
the top value equals the stack's last index, the stack is full.
Document shared on www.docsity.com
Downloaded by: thanhngan202 (vothithanhngann@gmail.com)
package Stack;
{
private int arr[];
private int top;
private int capacity;
// Constructor to initialize the stack
Stack(int size)
{
arr = new int[size];
capacity = size;
top = -1;
}
return -1;
}
}
}
Figure 57: Full code for stack in Java.
Figure 58: Program Result.
package EmployeeManagement;
import java.util.Scanner;
this.allowance = allowance;
}
public void enterInformation(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter ID: ");
id = scanner.nextLine();
System.out.println("Enter name: ");
name = scanner.nextLine();
System.out.println("Enter age: ");
age = scanner.nextInt();
System.out.println("Enter salary: ");
salary = scanner.nextFloat();
System.out.println("Enter allowance: ");
allowance = scanner.nextFloat();
}
}
And here is the EmployeeManagement source code which performance some function such as
sort, find, … and also displays the menu choices for user.
package EmployeeManagement;
import java.util.Objects;
import java.util.Scanner;
public class EmployeeManagement {
static Employee[] ls = new Employee[100];
static int index = 0;
void inputs(){
Scanner scanner = new Scanner(System.in);
String choice;
do {
Employee employee = new Employee();
employee.enterInformation();
ls[index] = employee;
index++;
System.out.println("You want to continue? (y/n)");
choice = scanner.next();
Document shared on www.docsity.com
Downloaded by: thanhngan202 (vothithanhngann@gmail.com)
}while (choice.equalsIgnoreCase("y"));
}
void outputs(){
System.out.println("List employees");
System.out.println("ID\t\t Name\t Age\tSalary\t\t Allowance");
for (int i = 0; i<index;i++){
Employee employee = ls[i];
System.out.printf("%1s %10s %5d
",employee.id,employee.name,employee.age);
System.out.printf("%5s %12s\n",employee.salary,employee.allowance);
}
}
void displayWithoutAllowance(){
System.out.println("List employees zero commission");
System.out.println("ID\t\t Name\t Age\tSalary\t\t Allowance");
for (int i = 0; i<index;i++){
Employee employee = ls[i];
if (employee.allowance == 0) {
System.out.printf("%1s %10s %5d
",employee.id,employee.name,employee.age);
System.out.printf("%5s
%12s\n",employee.salary,employee.allowance);
}
}
}
void findName(String name){
System.out.println("List employees");
System.out.println("ID\t\t Name\t Age\tSalary\t\t Allowance");
for (int i = 0; i < index; i++) {
if (Objects.equals(ls[i].name, name)){
Employee employee=ls[i];
System.out.printf("%1s %10s %5d
",employee.id,employee.name,employee.age);
System.out.printf("%5s %12s\n",employee.salary,employee.allowance);
}
}
}
void Sort(){
System.out.println("Sort by name");
for (int i = 0; i < index; i++) {
int min=i;
Document shared on www.docsity.com
for (int j = i;Downloaded
j < index; j++)
by: thanhngan202 {
(vothithanhngann@gmail.com)
if (ls[j].name.compareToIgnoreCase(ls[min].name)<0){
min=j;
Employee employee=ls[i];
ls[i]=ls[min];
ls[min]=employee;
}
}
}
}
void updateAllowance(float newAllowance,String id){
for (int i = 0; i < index; i++) {
if (ls[i].id.compareToIgnoreCase(id)==0){//found
Employee employee=ls[i];
ls[i].allowance =ls[i].allowance + newAllowance;
System.out.println("Update commission");
System.out.println("List employees");
System.out.println("ID\t\t Name\t Age\tSalary\t\t Allowance");
System.out.printf("%1s %10s %5d
",employee.id,employee.name,employee.age);
System.out.printf("%5s %12s\n",employee.salary,employee.allowance);
}
}
}
public static void showMenu() {
System.out.println("-------------------- Menu ---------------------");
System.out.println("1. Input");
System.out.println("2. Display Employee's List");
System.out.println("3. Find By Name");
System.out.println("4. Sort By Name");
System.out.println("5. Update Allowance");
System.out.println("6. Display employee who don't have allowance");
System.out.println("0. exit.");
System.out.println("-----------------------------------------------");
System.out.print("Please choose: ");
}
public static void Option(EmployeeManagement employeeManagement){
Scanner scanner = new Scanner(System.in);
String choose = null;
boolean exit = false;
// show menu
Document shared on www.docsity.com
showMenu(); Downloaded by: thanhngan202 (vothithanhngann@gmail.com)
while (true) {
choose = scanner.nextLine();
switch (choose) {
case "1":
employeeManagement.inputs();
break;
case "2":
employeeManagement.outputs();
break;
case "3":
System.out.println("Enter employee's name to find: ");
String name = scanner.nextLine();
employeeManagement.findName(name);
break;
case "4":
employeeManagement.Sort();
employeeManagement.outputs();
break;
case "5":
System.out.println("Enter id to update");
String id = scanner.nextLine();
System.out.println("Enter new allowance");
float newAllowance = scanner.nextFloat();
employeeManagement.updateAllowance(newAllowance,id);
break;
case "6":
employeeManagement.displayWithoutAllowance();
break;
case "0":
System.out.println("exited!");
exit = true;
break;
default:
System.out.println("invalid! please choose action in below
menu:");
break;
}
if (exit) {
break;
}
Document shared on www.docsity.com
// show menu Downloaded by: thanhngan202 (vothithanhngann@gmail.com)
showMenu();
}
}
public static void main(String[] args) {
EmployeeManagement employeeManagement = new EmployeeManagement();
Option(employeeManagement);
}
}
Figure 60: Employee Management Source Code.
This is the menu option for the user when they have onlined the app.
The second option is display the employee’s list and here is the result of this.
When they input the name they want, the information of that employee will display.
The fourth option is sort by name, this option will sort names alphabetically and here is the
result of this.
After sort:
The fifth option is update new allowance for the employee, when they chose option 5 the
system will display the place where you input employee’s id and new allowance for that
employee.
After Update:
Finally, the last option is display employee who do not have allowance. In this option the
employee who have the allowance equal to 0 will display to the screen.
Weak points:
+ Format of the report is not good
+ Writing skill is limited.