Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Recursion, Linked List Queue & Deque

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

FAKULTI TEKNOLOGI

KEJURUTERAAN KELAUTAN
DAN INFORMATIK

2019/2020

DATA STRUCTURE & ALGORITHM

Lab 5: Recursion,
Linked List Queue
& Deque

VERSION 1
STUDENT INFORMATION

PLEASE FILL IN YOUR DETAILS:

NAME: TEOH YI YIN

MATRIC NUMBER:S58798

GROUP:K3

LAB:CISCO

DATE:23/11/2021

i
TABLE OF CONTENTS
INSTRUCTIONS .......................................................................................................................... 1
TASK 1: Apply And Test The Implementation Of Recursion ...................................................... 2
TASK 2: Implementing Queue Using Linked List ........................................................................ 7
TASK 3: Using DEQUE Built-In Class ......................................................................................... 15
TASK 4: Programming Assignment Using Deque .................................................................... 18

ii
INSTRUCTIONS

Manual makmal ini adalah untuk kegunaan pelajar-pelajar Fakulti Teknologi Kejuruteraan
Kelautan dan Informatik, Universiti Malaysia Terengganu (UMT) sahaja. Tidak dibenarkan
mencetak dan mengedar manual ini tanpa kebenaran rasmi daripada penulis.

Sila ikuti langkah demi langkah sebagaimana yang dinyatakan di dalam manual.

This laboratory manual is for use by the students of the Faculty of Ocean Engineering Technology
and Informatics, Universiti Malaysia Terengganu (UMT) only. It is not permissible to print and
distribute this manual without the official authorisation of the author.

Please follow step by step, as described in the manual.

1
TASK 1: APPLY AND TEST THE IMPLEMENTATION OF RECURSION

OBJECTIVE

In this task, students must be able to:

• Apply the implementation recursion.


• Test the implementation

ESTIMATED TIME

[45 Minutes]

DEFINITION OF RECURSION
Recursion is a basic programming technique you can use in Java, in which a method calls itself
to solve some problem. A method that uses this technique is recursive. Many programming
problems can be solved only by recursion, and some problems that can be solved by other
techniques are better solved by recursion.

One of the classic problems for introducing recursion is calculating the factorial of an integer.
The factorial of any given integer — call it n so that you sound mathematical — is the product of
all the integers from 1 to n. Thus, the factorial of 4 is 24: 4 x 3 x 2 x 1.

The recursive way to look at the factorial problem is to realize that the factorial for any given
number n is equal to n times the factorial of n–1, provided that n is greater than 1. If n is 1, the
factorial of n is 1.

This definition of factorial is recursive because the definition includes the factorial method itself.
It also includes the most important part of any recursive method: an end condition. The end
condition indicates when the recursive method should stop calling itself. In this case, when n is
1, it just returns 1. Without an end condition, the recursive method keeps calling itself forever.

2
Figure 1: Recursion Trace for the factorial of 4

STEPS:
1. Open Netbeans and create new java application project.
2. Name your project as RecursionExperiment and click finish.
3. Change author profiles to :
a. Name :
b. Program: <put your program. E.g., SMSK(SE) or SMSK with
IM
c. Course : CSF3104
d. Lab : <enter lab number>
e. Date : <enter lab date>
4. In the same RecursionExperiment project’s package, create a new file named
Factorial.java and insert the following codes:

3
5. Insert a main method in the same file to test the above codes. Put 6 as your input.
Answer:
/**
* @author
* Name: TEOH YI YIN
* Program: SMSK(SE)
* Course: CSF3104
* Lab: 5
* Date: 23/11/2021
*/

public class Factorial {


public static int factorial(int n) throws IllegalArgumentException{
if (n<0){
throw new IllegalArgumentException();
}else if (n == 0){
return 1;
}else{
return n*factorial(n-1);
}
}

public static void main(String[] args) {


System.out.println(factorial(6));
}
}
//Output: 720

4
6. Draw a recursion trace for an execution of your input.
Hint: You may draw using Ms Word/Ms Paint or draw it manually. Snap the photo of your
drawing and upload it here.

5
QUESTIONS
1. Where can we apply recursion in data structure?
Answer:
When we need to call the same function iteratively, in reverse order.

2. Explain what is the meaning of ‘base case’ and ‘recursive call’. What will happen when
there is no base case in our recursive method?
Answer:
Base case is a problem that we know the answer. It stops the recursion from
continuing execution.
Recursive call is when a function A calls itself directly or calls a function B that in
turn calls the function A.
When there is no base case in our recursive method, recursive call will go on making
until the program crash.

6
TASK 2: IMPLEMENTING QUEUE USING LINKED LIST

OBJECTIVE

In this task, students will implement a queue using linked list as an alternative to array.

ESTIMATED TIME

[45 Minutes]

USING LINKED LIST FOR QUEUE


A queue is a First In First Out (FIFO) data structure where the first item inserted is the first to be
removed. In a queue items are inserted at the rear and removed from the front of the queue.

Following image shows an implementation of Queue as linked list with front and rear references.

OPERATIONS IN QUEUE
As we know, there are three operations are implemented for a Queue:

insert: To insert an item at the rear of the queue.


remove: To remove an item from the front of the queue.
peek: Read value from the front of the queue without removing it.

STEPS:
1. Open Netbeans and create new java application project.
2. Name your project as LinkedListQExperiment and click finish.
3. Change author profiles to :
a. Name :
b. Program: <put your program. E.g., SMSK(SE) or SMSK with
IM

7
c. Course : CSF3104
d. Lab : <enter lab number>
e. Date : <enter lab date>

4. In the same LinkedListQExperiment project’s package, create a new file named


LinkedListQueue.java and insert the following codes:

8
9
5. Create a test class for the LinkedListQueue. Use 2,1,0,3,0 as your input. Sample
output:

6. Copy and paste your Java codes into text box below:
package LinkedListQExperiment;

/**
* @author
10
* Name: TEOH YI YIN
* Program: SMSK(SE)
* Course: CSF3104
* Lab: 5
* Date: 23/11/2021
*/

public class LinkedListQueue {


Node front;
Node rear;

public LinkedListQueue(){
front=null;
rear=null;
}

//class for node


private class Node{
//data
int i;
Node next;

Node(int i){
this.i=i;
}

public void displayData(){


System.out.println("i= "+i);
}
}

//Linked List Operations


public void insertLast(int i){
Node newNode = new Node(i);
if(isEmpty()){
front=newNode;
}else{
rear.next=newNode; //previous last point to new node

11
}
rear=newNode;
}

public int removeFirst(){


int temp=front.i;

if(front.next == null){ //if no node left after deledting node


rear=null;
}

front = front.next; //front pointing to next element


return temp;
}

public void displayList(){


Node current = front;

while (current != null){


current.displayData();
current = current.next;
}
}

public int nodeData(){


return front.i;
}

public boolean isEmpty(){


return front == null;
}

//Queue Operations
public void insert(int item){
insertLast(item);
}

public int remove(){

12
if (isEmpty()){
throw new RuntimeException("Queue is empty..");
}
return removeFirst();
}

public int peek(){


if (isEmpty()){
throw new RuntimeException("Queue is empty..");
}
return nodeData();
}
}

package LinkedListQExperiment;

/**
* @author
* Name: TEOH YI YIN
* Program: SMSK(SE)
* Course: CSF3104
* Lab: 5
* Date: 23/11/2021
*/

public class LinkedListQueueTest {


public static void main(String[] args){
LinkedListQueue linkedlistqueue = new LinkedListQueue();

System.out.println("-- Displaying Queue Data --");


linkedlistqueue.insert(2);
linkedlistqueue.insert(1);
linkedlistqueue.insert(0);
linkedlistqueue.insert(3);
linkedlistqueue.insert(0);
linkedlistqueue.displayList();

System.out.println("Item peeked- " + linkedlistqueue.peek());

13
System.out.println("-- Removing Queue Elements --");
System.out.println("Item removed- " + linkedlistqueue.remove());
System.out.println("Item removed- " + linkedlistqueue.remove());
}
}

QUESTIONS
1. Describe the advantage(s) of using linked list for queue compared to array.
Answer:
By using linked list, less memory wastage due to the use of dynamic memory
allocation. Besides that, the list elements can be easily inserted and removed without
reallocation the entire queue structure.

2. Where can we apply queue in the software development?


Answer:
When we need to manage group of objects in the order in which the first coming in will
gets out first.

14
TASK 3: USING DEQUE BUILT-IN CLASS

OBJECTIVE

During this activity, students will apply double-ended queue (deque) in a simple programming
task. Student should understand how deque works.

ESTIMATED TIME

[30 Minutes]

INTRODUCTION

Java Deque Interface is a linear collection that supports element insertion and removal at both
ends. Deque is an acronym for "double ended queue".

STEPS:
1. Open previously created Netbeans project.
2. Create a new class named DequeDemo.
3. In DequeDemo.java, import Deque and ArrayDeque class from java.util
package:

4. Type the following codes into your Netbeans editor:

15
5. Save, compile and run the codes. Observe the output and explain how the below methods
work:
a. offer()
b. add()
c. offerFirst()
d. pollLast()

Answer:

a. offer() method will insert the data into the array accordingly and throw boolean
false when the queue is full.
b. add() method will insert the data into the array accordingly and throw an
exception when the queue is full.
c. offerFirst() method will insert the data to the front of the array.
d. pollLast() method will remove the data at the last of the array.

16
QUESTIONS
1. Explain the difference between linear queue and double-ended queue.
Answer:
In linear queue, insertions made at the end of queue and deletions made at the front of
queue.
In double-ended queue, insertions and deletions are made either at the front or the end
of the queue.

17
TASK 4: PROGRAMMING ASSIGNMENT USING DEQUE

OBJECTIVE

To implement a PhoneBook class and create a simple program to save and retrieve a Phone
Book records.

ESTIMATED TIME

[30 Minutes]

INSTRUCTIONS:
Given here is the structure of a class named PhoneBook:

PhoneBook
id: int
name: String
phoneNumber: String

1. Implement the above class using Java. Create a parameterized constructor that accepts
three parameters, as described in the PhoneBook class diagram.
2. Next, create a demo class to insert and traverse records in the PhoneBook. Use Deque
and ArrayQueue in your implementation.
3. Use the following dataset to test your program:
a. Pendaftar UMT: 096684342
b. Jabatan Pengurusan Akademi UMT: 096684219
c. Fakulti Teknologi Kejuruteraan Kelautan dan Informatik: 096683220
4. Bonus task: Create a search function to retrieve a record from your PhoneBook program.
As example, user enters “Pendaftar” as an input, and then your program will display
“096684342” as the output.
5. Copy and paste your finished codes into the below text box:
package PhoneBook;

/**
* @author
* Name: TEOH YI YIN
* Program: SMSK(SE)
* Course: CSF3104
* Lab: 5
* Date: 23/11/2021

18
*/

public class PhoneBook {


int id;
String name;
String phoneNumber;

public PhoneBook(int id, String name, String phoneNumber){


this.id=id;
this.name=name;
this.phoneNumber=phoneNumber;
}

public int getId() {


return id;
}

public void setId(int id) {


this.id = id;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public String getPhoneNumber() {


return phoneNumber;
}

public void setPhoneNumber(String phoneNumber) {


this.phoneNumber = phoneNumber;
}

public String toString(){

19
return "ID : " + id + "\nName : " + name + "\nPhone Number : " + phoneNumber + "\n";
}
}

package PhoneBook;

/**
* @author
* Name: TEOH YI YIN
* Program: SMSK(SE)
* Course: CSF3104
* Lab: 5
* Date: 23/11/2021
*/

import java.util.Deque;
import java.util.ArrayDeque;
import java.util.Scanner;

public class PhoneBookTest {


public static void main(String[] args){

Deque<PhoneBook> phonebook = new ArrayDeque<>();


phonebook.add(new PhoneBook(1,"Pendaftar UMT","096684342"));
phonebook.add(new PhoneBook(2,"Jabatan Pengurusan Akademi
UMT","096684219"));
phonebook.add(new PhoneBook(3,"Fakulti Teknologi Kejuruteraan Kelautan dan
Informatik","096683220"));

System.out.println("-- Phone Book Records --");


for(PhoneBook r : phonebook){
System.out.println(r);
}

Scanner input = new Scanner(System.in);


boolean found = false;

System.out.print("Enter name for Searching : ");

20
String name = input.nextLine();

for(PhoneBook r : phonebook){
if(r.getName().equals(name)){
System.out.println(r.getPhoneNumber());
found = true;
}
}

if(found == false){
System.out.println("Number Not Found!");
}
}
}

Finally, read the instruction regarding submission carefully. Submit your answer using the link
provided in Oceania UMT. Please ensure your codes are submitted to the correct group.

21

You might also like