Task 4
Task 4
public:
LinkedList () {
setHead (NULL);
}
bool isEmpty () {
return getHead () == NULL;
}
void addOnHead (int data) {
/*
Steps
1. if the list is empty
1.1. insert/add a new node at the head
2. if the list is not empty
2.1. Create a temporary pointer of Node type and store the reference of
the created node with data in it
2.2. Next part of temp node point/refer to the node which head is
referring to
2.3. Head node will start referring to the node which temp node is
referring to
*/
void printList () {
/*
Steps
1. if the list is not empty
1.1. Create a pointer named temp and store the address of node head is
referring to
1.2. Check if temp is not NULL
1.2.1. print the data part of temp
1.2.2. move temp to the next part
1.2.3. Repeat 1.2.
*/
if (!isEmpty()){ //step 1
Node* prev = searchDataBefore(key); //step 1.1
if (getHead()->getData() == key) { //step 2
addOnHead(data); //step 2.1
}
if (prev != NULL) { //step 3
Node* newNode = new Node(data); //step 3.1
newNode->setNext(prev->getNext()); //step 3.2
prev->setNext(newNode); //step 3.3
}
else {
//step 4
cout<<"there is no specific node you want to insert before "<<endl;
//step 4.1
}
}
}
bool removeData(int key) {
if (!isEmpty()) {
Node* temp = getHead();
Node* prev = NULL;
while (temp != NULL && temp->getData() != key) {
prev = temp;
temp = temp->getNext();
}
if (temp != NULL) {
if (prev == NULL) {
setHead(temp->getNext());
} else {
prev->setNext(temp->getNext());
}
delete temp;
return true;
}
}
return false;
}
};
#define SIZE 10
class Hashing {
public:
Hashing() {
for (int index = 0; index < SIZE; index += 1) {
array[index] = new LinkedList();
}
}
void printHashTable() {
for (int index = 0; index < SIZE; index += 1) {
cout << "Index " << index << ": ";
array[index]->printList();
}
}
private:
int hashFunction(int key) {
return ((key + 3) * 5) % SIZE;
}
LinkedList* array[SIZE];
};
int main() {
Hashing obj;
obj.insertData(2);
obj.insertData(3);
obj.insertData(4);
obj.insertData(5);
obj.insertData(6);
obj.insertData(32);
obj.insertData(12);
obj.insertData(22);
obj.updateData(5, 33);
obj.removeData(12);
obj.printHashTable();
cout << "Value index: " << obj.searchData(4) << endl;
obj.removeData(4);
cout << "Value index: " << obj.searchData(4) << endl;
return 0;
}