0% found this document useful (0 votes)
46 views18 pages

CMP2006 LabWorksheet 6 LinkedList

The document describes a C++ implementation of a linked list to store student data including ID, name, and GPA. It includes classes for a Student node and LinkedList, and methods to insert nodes, count nodes, search for a node by ID, and display the list.

Uploaded by

Relax Nation
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)
46 views18 pages

CMP2006 LabWorksheet 6 LinkedList

The document describes a C++ implementation of a linked list to store student data including ID, name, and GPA. It includes classes for a Student node and LinkedList, and methods to insert nodes, count nodes, search for a node by ID, and display the list.

Uploaded by

Relax Nation
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/ 18

UNIVERSITY OF TECHNOLOGY JAMAICA

FACULTY OF COMPUTING AND ENGINEERING


SCHOOL OF COMPUTING AND INFORMATION TECHNOLOGY

Data Structures (CMP2006)

Lab Worksheet #6 – Linked List

Scenario
Utech has asked you to create a program that will track all its students’ details. Each student has
an Id, Name and GPA.

C++ Implementation

//Student Class

#ifndef Student_H
#define Student_H

#include <iostream>
using namespace std;

//Data Portion
class Student
{
//Class attributes
private:
int Id;
string Name;
float GPA;

public:
// Default Constructor
Student()
{
Id = 0;
Name = "";
GPA = 0.0f;
}

// Primary Constructor
Student(int id, string name, float gpa)
{
Id = id;
Name = name;
GPA = gpa;
}

// Copy Constructor
Student(Student &s)

Updated by Philip Smith – June 2019 Page 1 of 18


{
Id = s.Id;
Name = s.Name;
GPA = s.GPA;
}

//Accessors
int GetId()
{
return Id;
}
string GetName()
{
return Name;
}
float GetGPA()
{
return GPA;
}

//Mutators
void SetId(int id)
{
Id = id;
}
void SetName(string name)
{
Name = name;
}
void SetGPA(float gpa)
{
GPA = gpa;
}

void Display()
{
cout<<"Id: "<< Id << ", Name: " << Name << ", GPA: " << GPA;
}

};

#endif

//Node Class

#ifndef Node_H
#define Node_H

#include "Student.h"

//Node object
class Node
{
//Class Attributes
private:
Student Data; //Data portion - Composition
Node * NextNode; //Link portion (dynamically declared)

public:
//default constructor

Updated by Philip Smith – June 2019 Page 2 of 18


Node():Data() //initialize (composition) student using its default constructor
{
NextNode = NULL;
}

//primary constructor 1
Node(Student data, Node * nextNode):Data(data) //initialize (composition) student using its copy
constructor
{
NextNode = nextNode;
}

//primary constructor 2 || 99%


Node(Student data):Data(data) //initialize (composition) student using its copy constructor
{
NextNode = NULL; //set the next node to null
}

//primary constructor 3
Node(int id, string name, float gpa):Data(id, name, gpa) //initialize (composition) student using
its primary constructor
{
NextNode = NULL; //set the next node to null
}

//copy constructor
Node(Node *node)
{
Data = node->Data;
NextNode = node->NextNode;
}

//Accessors
Student GetData()
{
return Data;
}

Node * GetNextNode()
{
return NextNode;
}

//Mutators
void SetData(Student data)
{
Data = data;
}

void SetNextNode(Node * nextNode)


{
NextNode = nextNode;
}

};

#endif

Updated by Philip Smith – June 2019 Page 3 of 18


//LinkedList Class

#ifndef LinkedList_H
#define LinkedList_H

#include "Node.h"

//Node object
class SinglyLinkedList
{
//Class attribues
private:
Node * Head; //Head should point to the first element in list

public:

//default constructor
SinglyLinkedList() //Creates an empty list || 99% used
{
Head = NULL;
}

//primary
SinglyLinkedList(Node * h)//Creates a list with one element in there
{
Head = h;
}

//Accessors
Node * GetHead()
{
return Head;
}

//Mutator
void SetHead(Node * head)
{
Head = head;
}

void InsertAtFront(Student dataToInsert)


{
Node * temp; //declare temp as a pointer to the memory address of a node
temp = new Node; //calls default constructor and attempts to reserve memory for temp

if(temp != NULL) //if memory was allocated successfully


{
temp->SetData(dataToInsert); //set the data of the new node
temp->SetNextNode(NULL); //set the link portion to point to NULL

if(Head == NULL) //if the list is empty


{
Head = temp;
}
else //if the list was not empty
{
temp->SetNextNode(Head); //points temps next node to head
Head = temp; //makes temp the new first node in the list
}
}
else //if memory was not allocated successfully

Updated by Philip Smith – June 2019 Page 4 of 18


{
cerr<<"Error! List is full (Out of Memory), can NOT add a new node"<<endl;
}
}

void InsertAtBack(Student dataToInsert)


{
Node * temp1, *temp2; //temp1 is the new node to be added to list || temp2 is our temp pointer
to assist in traversing the list
temp1 = new Node; //initialize temp1 using the default constructor
if(temp1 != NULL)
{
temp1->SetData(dataToInsert); //set the data of the new node
temp1->SetNextNode(NULL); //set the link portion to point to NULL

if(Head == NULL) //if the list is empty


{
Head = temp1; //set head to point to the new node to be added to list
}
else //if the list was not empty
{
temp2 = Head; // initialize temp node to point to first element in list
while(temp2->GetNextNode() != NULL) //while we are not at the last node in the list
{
temp2 = temp2->GetNextNode(); //move the current node (temp2) to IT'S next node
}
temp2->SetNextNode(temp1); //set the link portion (NextNode) of the last node to point
to the new node we are trying to add to the list
}

}
else //if memory was not allocated successfully
{
cerr<<"Error! List is full (Out of Memory), can NOT add a new node"<<endl;
}
}

void InsertAtBack(int id, string name, float gpa)


{
Node * temp1 = new Node(id, name, gpa); // initialize temp1 using the primary constructor 3 |
Reserve Memory Space
if(temp1 != NULL) //if memory was allocated successfully
{
if(Head == NULL) //if the list is empty
{
Head = temp1; //set head to point to the new node to be added to list
}
else //if the list was not empty
{
Node * temp2 = Head; // initialize temp node to point to first element in list
while(temp2->GetNextNode() != NULL) //while we are not at the last node in the list
{
temp2 = temp2->GetNextNode(); //move the current node (temp2) to IT'S next node
}
temp2->SetNextNode(temp1); //set the link portion (NextNode) of the last node to point
to the new node we are trying to add to the list
}
}
else //if memory was not allocated successfully
{
cerr<<"Error! List is full (Out of Memory), can NOT add a new node"<<endl;
}
}

Updated by Philip Smith – June 2019 Page 5 of 18


int CountNodes()
{
int count = 0;// initialize counter
Node * curr = Head; //initialize curr to point to first element in list
while(curr != NULL) //while curr is pointing to a valid node
{
count++; //increment counter
curr = curr->GetNextNode(); //point curr to IT'S next node
}
return count; //return number of elements in list
}

bool SearchForANode(int studId)


{
bool isFound = false;

Node * curr = Head; //point curr to the first element in the list.
while (curr != NULL) //while curr is pointing to a valid node
{
if(curr->GetData().GetId() == studId) //if the curr node has the data we are searching for
{
isFound = true; //set the bool to true (element found)
break; //jump out of loop
}
curr = curr->GetNextNode(); //point curr to IT'S next node
}

return isFound;
}

void DisplayList()
{
Node * curr = Head; //point curr to the first element in the list.
while (curr != NULL) //while curr is pointing to a valid node
{
cout<<"[";
curr->GetData().Display(); //display the data for that node
cout<<"]->";
curr = curr->GetNextNode(); //point curr to IT'S next node
}
cout<<"NULL";
}

bool IsEmpty()
{
if(Head == NULL) //if the list is empty
{
return true; //return TRUE - list is empty
}
return false; //List is not empty
}

bool IsFull()
{
Node *temp = new Node; //attempt to reserve space for a new node by calling default
constructor
if(temp != NULL) //if memory was allocated successfully
{
delete temp; //deallocate the memory for temp

Updated by Philip Smith – June 2019 Page 6 of 18


return false;
}
return true;
}

Student DeleteANode(int studId)


{

Student dataToReturn;

if(!IsEmpty())
{
Node *curr = Head, *prev=NULL; //point curr to the first element in the list.

while(curr != NULL) //while curr is pointing to a valid node; go through list


{
if(curr->GetData().GetId() == studId) //if the curr node has the data we are searching
for
{
if(curr == Head) //if curr is pointing to head (if we are deleting the first node
in list)
{
Head = Head->GetNextNode(); //point head to IT's next node
}
else
{
prev->SetNextNode(curr->GetNextNode()); //set the next node of "prev" to
"curr" next node
}
dataToReturn = curr->GetData(); //capture data from node to be deleted.
delete curr; //deallocate memory for curr
break; //jump out of loop
}
prev = curr;
curr = curr->GetNextNode(); //point curr to IT's next ndoe
}

}
else
{
cerr<<"The list is empty; there is nothing to delete!"<<endl;
}

return dataToReturn;
}

};

#endif

//Main/Driver Class

#include "SinglyLinkedList.h"

int main()

Updated by Philip Smith – June 2019 Page 7 of 18


//create students using primary constructor

Student stud1(123, "Jane Doe", 3.7f);

Student stud2(222, "John Smith", 4.7f);

Student stud3(333, "Jessie Jackson", 2.7f);

//declare an empty linked list using its default constructor

SinglyLinkedList *list = new SinglyLinkedList;

/*

list->InsertAtFront(stud1);

list->InsertAtFront(stud2);

list->InsertAtFront(stud3);

*/

cout<<"\n\nList Empty: "<<list->IsEmpty()<<endl;

cout<<"List Full: "<<list->IsFull()<<endl;

cout<<"Number of elements in list: " << list->CountNodes()<<endl;

list->InsertAtBack(stud1);

list->InsertAtBack(stud2);

list->InsertAtBack(stud3);

list->DisplayList();

//cout<<"\n\nNumber of elements in list: " << list->CountNodes()<<endl;

// cout<<"Check if student with id 123 is found in list: "<< list->SearchForANode(123)<<endl;

//cout<<"Check if student with id 321 is found in list: "<< list->SearchForANode(321)<<endl;

//cout<<"List Empty: "<<list->IsEmpty()<<endl;

//cout<<"List Full: "<<list->IsFull()<<endl;

cout<<"\n\nData deleted from list: ";

list->DeleteANode(333).Display();

cout<<"\n\n";

//\n\nDelete function called for 333\n\n";

Updated by Philip Smith – June 2019 Page 8 of 18


list->DisplayList();

return 0;

Updated by Philip Smith – June 2019 Page 9 of 18


Java Implementation

//Data Class (Student)


class Student

//Class attributes

private int Id;

private String Name;

private float GPA;

// Default Constructor

public Student()

Id = 0;

Name = "";

GPA = 0.0f;

// Primary Constructor

public Student(int id, String name, float gpa)

Id = id;

Name = name;

GPA = gpa;

// Copy Constructor

public Student(Student s)

Id = s.Id;

Name = s.Name;

GPA = s.GPA;

//Accessors

Updated by Philip Smith – June 2019 Page 10 of 18


public int GetId()

return Id;

public String GetName()

return Name;

public float GetGPA()

return GPA;

//Mutators

public void SetId(int id)

Id = id;

public void SetName(String name)

Name = name;

public void SetGPA(float gpa)

GPA = gpa;

public void Display()

System.out.print("Id: " + Id + ", Name: " + Name + ", GPA: " + GPA);

@Override

public String toString()

Updated by Philip Smith – June 2019 Page 11 of 18


return "Id: " + Id + ", Name: " + Name + ", GPA: " + GPA;

//Node Class

//Node object
class Node
{
//Class Attributes

private Student Data; //Data portion - Composition


private Node NextNode; //Link portion (dynamically declared)

//default constructor
public Node()
{
Data = new Student();//initialize (composition) student using its default constructor
NextNode = null;
}

//primary constructor 1
public Node(Student data, Node nextNode)
{
Data = new Student(data); //initialize (composition) student using its copy constructor
NextNode = nextNode;
}

//primary constructor 2 || 99%


public Node(Student data)
{
Data = new Student(data); //initialize (composition) student using its copy constructor
NextNode = null; //set the next node to null
}

//primary constructor 3
public Node(int id, String name, float gpa)
{
Data = new Student(id, name, gpa); //initialize (composition) student using its primary
constructor
NextNode = null; //set the next node to null
}

//copy constructor
public Node(Node node)
{
Data = node.Data;
NextNode = node.NextNode;
}

//Accessors
public Student GetData()
{

Updated by Philip Smith – June 2019 Page 12 of 18


return Data;
}

public Node GetNextNode()


{
return NextNode;
}

//Mutators
public void SetData(Student data)
{
Data = data;
}

public void SetNextNode(Node nextNode)


{
NextNode = nextNode;
}

//LinkedList Class

//List object
class SinglyLinkedList
{
//Class attribues
private Node Head; //Head should point to the first element in list

//default constructor
public SinglyLinkedList() //Creates an empty list || 99% used
{
Head = null;
}

//primary
public SinglyLinkedList(Node h)//Creates a list with one element in there
{
Head = h;
}

//Accessors
public Node GetHead()
{
return Head;
}

//Mutator
public void SetHead(Node head)
{
Head = head;
}

public void InsertAtFront(Student dataToInsert)


{
Node temp; //declare temp as a pointer to the memory address of a node
temp = new Node(); //calls default constructor and attempts to reserve memory for tem p

Updated by Philip Smith – June 2019 Page 13 of 18


if(temp != null) //if memory was allocated successfully
{
temp.SetData(dataToInsert); //set the data of the new node
temp.SetNextNode(null); //set the link portion to point to NULL

if(Head == null) //if the list is empty


{
Head = temp;
}
else //if the list was not empty
{
temp.SetNextNode(Head); //points temps next node to head
Head = temp; //makes temp the new first node in the list
}
}
else //if memory was not allocated successfully
{
System.err.println("Error! List is full (Out of Memory), can NOT add a new node");
}
}

public void InsertAtBack(Student dataToInsert)


{
Node temp1, temp2; //temp1 is the new node to be added to list || temp2 is our temp pointer to
assist in traversing the list
temp1 = new Node(); //initialize temp1 using the default constructor
if(temp1 != null)
{
temp1.SetData(dataToInsert); //set the data of the new node
temp1.SetNextNode(null); //set the link portion to point to NULL

if(Head == null) //if the list is empty


{
Head = temp1; //set head to point to the new node to be added to list
}
else //if the list was not empty
{
temp2 = Head; // initialize temp node to point to first element in list
while(temp2.GetNextNode() != null) //while we are not at the last node in the list
{
temp2 = temp2.GetNextNode(); //move the current node (temp2) to IT'S next node
}
temp2.SetNextNode(temp1); //set the link portion (NextNode) of the last node to point
to the new node we are trying to add to the list
}

}
else //if memory was not allocated successfully
{
System.err.println("Error! List is full (Out of Memory), can NOT add a new node");
}
}

public void InsertAtBack(int id, String name, float gpa)


{
Node temp1 = new Node(id, name, gpa); // initialize temp1 using the primary constructor 3 |
Reserve Memory Space
if(temp1 != null) //if memory was allocated successfully
{
if(Head == null) //if the list is empty
{
Head = temp1; //set head to point to the new node to be added to list

Updated by Philip Smith – June 2019 Page 14 of 18


}
else //if the list was not empty
{
Node temp2 = Head; // initialize temp node to point to first element in list
while(temp2.GetNextNode() != null) //while we are not at the last node in the list
{
temp2 = temp2.GetNextNode(); //move the current node (temp2) to IT'S next node
}
temp2.SetNextNode(temp1); //set the link portion (NextNode) of the last node to point
to the new node we are trying to add to the list
}
}
else //if memory was not allocated successfully
{
System.err.println("Error! List is full (Out of Memory), can NOT add a new no de");
}
}

public int CountNodes()


{
int count = 0;// initialize counter
Node curr = Head; //initialize curr to point to first element in list
while(curr != null) //while curr is pointing to a valid node
{
count++; //increment counter
curr = curr.GetNextNode(); //point curr to IT'S next node
}
return count; //return number of elements in list
}

public boolean SearchForANode(int studId)


{
boolean isFound = false;

Node curr = Head; //point curr to the first element in the list.
while (curr != null) //while curr is pointing to a valid node
{
if(curr.GetData().GetId() == studId) //if the curr node has the data we are searching for
{
isFound = true; //set the bool to true (element found)
break; //jump out of loop
}
curr = curr.GetNextNode(); //point curr to IT'S next node
}

return isFound;
}

public void DisplayList()


{
Node curr = Head; //point curr to the first element in the list.
while (curr != null) //while curr is pointing to a valid node
{
System.out.print("["+ curr.GetData() + "]->");
curr = curr.GetNextNode(); //point curr to IT'S next node
}
System.out.println("NULL");
}

public boolean IsEmpty()

Updated by Philip Smith – June 2019 Page 15 of 18


{
if(Head == null) //if the list is empty
{
return true; //return TRUE - list is empty
}
return false; //List is not empty
}

public boolean IsFull()


{
Node temp = new Node(); //attempt to reserve space for a new node by calling default
constructor
if(temp != null) //if memory was allocated successfully
{
temp = null; //delete temp; //deallocate the memory for temp
return false;
}
return true;
}

public Student DeleteANode(int studId)


{

Student dataToReturn = new Student();

if(!IsEmpty())
{
Node curr = Head, prev=null; //point curr to the first element in the list.

while(curr != null) //while curr is pointing to a valid node; go through list


{
if(curr.GetData().GetId() == studId) //if the curr node has the data we are searching
for
{
if(curr == Head) //if curr is pointing to head (if we are deleting the first node
in list)
{
Head = Head.GetNextNode(); //point head to IT's next node
}
else
{
prev.SetNextNode(curr.GetNextNode()); //set the next node of "prev" to "curr"
next node
}
dataToReturn = curr.GetData(); //capture data from node to be deleted.
curr = null;//delete curr; //deallocate memory for curr
break; //jump out of loop
}
prev = curr;
curr = curr.GetNextNode(); //point curr to IT's next ndoe
}

}
else
{
System.err.println("The list is empty; there is nothing to delete!");
}

return dataToReturn;
}

Updated by Philip Smith – June 2019 Page 16 of 18


//Main/Driver Class
public class Main

public static void main(String[] args)

//create students using primary constructor

Student stud1 = new Student(123, "Jane Doe", 3.7f);

Student stud2 = new Student(222, "John Smith", 4.7f);

Student stud3 = new Student(333, "Jessie Jackson", 2.7f);

//declare an empty linked list using its default constructor

SinglyLinkedList list = new SinglyLinkedList();

System.out.println("\n\nList Empty: " + list.IsEmpty());

System.out.println("List Full: "+list.IsFull());

System.out.println("Number of elements in list: " + list.CountNodes());

list.InsertAtBack(stud1);

list.InsertAtBack(stud2);

list.InsertAtBack(stud3);

list.DisplayList();

//cout<<"\n\nNumber of elements in list: " << list->CountNodes()<<endl;

//cout<<"Check if student with id 123 is found in list: "<< list->SearchForANode(123)<<endl;

//cout<<"Check if student with id 321 is found in list: "<< list->SearchForANode(321)<<endl;

//cout<<"List Empty: "<<list->IsEmpty()<<endl;

//cout<<"List Full: "<<list->IsFull()<<endl;

System.out.println("\n\nData deleted from list: " + list.DeleteANode(333)+ "\n");

Updated by Philip Smith – June 2019 Page 17 of 18


Exercises

1. Utech has engaged you as a software developer to manage scholarship opportunities that
the students may apply for. Each scholarship has a unique numeric identifier, a sponsor
and a cash value. Create a program that would demonstrate the use of a singly linear
linked list that may prompt the user with the following menu options:
a. Add Scholarship (Adds element to the middle of the list)
b. Search Scholarship (prompts the user for an Id, then searches and displays all the
details of the scholarship if found; an appropriate message if not found)
c. Display All Scholarships (shows the details for all the scholarships in list format)
d. Count Scholarships (returns the number of scholarships in list)

2. Create a Doubly Linked List and a Circular Linked List that is able to manage a series of
numbers. Users should be able to:
a. Add new numbers to the back
b. Add new numbers to the front
c. Count and display the number of elements in list
d. Search the list for a particular number and indicate if it was found in the list or not

Updated by Philip Smith – June 2019 Page 18 of 18

You might also like