I've a homework task, where I've to sort linked list elements (strings) after first character in a string.
Example:
From: Pineapple->Apple->Ash->Abc->Pearl->Bonfire->Ball
To: Apple->Ash->Abc->Bonfire->Ball->Pineapple->Pearl (Only first char)
I made a function:
void insertionSort ()
{
first = current;
Node* insertionPointer = first;
current = current -> next;
for (start(); !end(); next()){ // Running through all list nodes
while (current != NULL) {
insertionPointer = first;
while(insertionPointer->next != current) {
if (insertionPointer->data.at(0) > current-> data.at(0)){ // Trying to sort strings alphabetically
// (after only first char)
string temp = current->data;
current->data = insertionPointer->data;
insertionPointer->data = temp;
}
else {
insertionPointer = insertionPointer->next;
}
}
}
}
}
But I get a segmentation fault - I guess that means I'm trying to get some information, that I can not access? Also, I'm not sure if:
if (insertionPointer->data.at(0) > current-> data.at(0))
Will compare strings first char? I'm just trying to experiment here. :(
Just to make sure, I'll post below also my whole code, so you can see how I structured lists and other functions. I'm new to this stuff - any information will be helpful.
Full program code:
#include <iostream>
#include <fstream>
#include <string>
#include <string.h>
using namespace std;
class Node
{
public:
string data;
Node *next;
Node (string city) { data = city; next = NULL; };
};
class List
{
protected:
Node *first, *last;
public:
Node *current;
public:
List () { first = last = current = NULL; };
void add_element (string city);
void delete_element ();
~List();
bool is_empty () { return (first == NULL); };
void start () { current = first; };
bool end () { return (current == NULL); };
void next(){if (!end())current = current -> next;};
void print();
void insertionSort ()
{
first = current;
Node* insertionPointer = first;
current = current -> next;
for (start(); !end(); next()){ // Running through all list nodes
while (current != NULL) {
insertionPointer = first;
while(insertionPointer->next != current) {
if (insertionPointer->data.at(0) > current->data.at(0)){ // Trying to sort strings alphabetically
// (after only first char)
string temp = current->data;
current->data = insertionPointer->data;
insertionPointer->data = temp;
}else{
insertionPointer = insertionPointer->next;
}
}
}
}
}
};
int main()
{
string s;
List l;
l.add_element("Pineapple");
l.add_element("Apple");
l.add_element("Ash");
l.add_element("Abc");
l.add_element("Pearl");
l.add_element("Bonfire");
l.add_element("Ball");
l.print();
cout << endl;
l.insertionSort();
l.print();
return 0;
}
void List::add_element (string city)
{
Node *p = new Node (city);
if (first == NULL) first = last = p;
else last = last -> next = p;
current = p;
};
void List::delete_element ()
{
Node *p = first;
if(!is_empty())
{ if (current == first) current = first-> next;
first = first -> next;
delete p;
if(is_empty())last = NULL;
}
};
void List::print()
{
for (start(); !end(); next())
{
cout << current->data << endl;
}
cout << endl;
};
List::~List()
{
while (!is_empty())
{
delete_element();
};
cout << "All memory of nodes deleted!"<< endl;
};
Your program is most likely crashing here:
while(insertionPointer->next != current) {
because insertionPointer has become null when you executed
insertionPointer = insertionPointer->next;
change the loop condition to
while(insertionPointer && insertionPointer->next != current) {
Related
I have a little problem which occurs after trying to execute function delete_all(). Any idea why Visual Studio is throwing me an error:
Invalid address specified to RtlValidateHeap, instruction __debugbreak() or something similar
Everything works perfect until I want to execute this function.
#include <iostream>
using namespace std;
struct node {
string name = "n1";
node* prev = NULL;
node* next = NULL;
};
node* add(node* first, string name) {
if (first == NULL) {
return NULL;
}
node* nowy = new node;
if (first->next == NULL) {
nowy->prev = first;
first->next = nowy;
}
else {
while (first->next != NULL) {
first = first->next;
}
nowy->prev = first;
first->next = nowy;
}
nowy->name = name;
return nowy;
}
void writeout(node* first) {
if (first == NULL) cout << "first = NULL";
while (first->next != NULL) {
cout << first->name;
cout << "\n";
first = first->next;
}
if (first->next == NULL) {
cout << first->name;
cout << "\n";
}
}
void delete_all(node* first) {
node* temp;
while (first != NULL) {
temp = first->next;
delete first;
first = temp;
}
}
int main()
{
node n1;
add(&n1, "n2");
add(&n1, "n3");
writeout(&n1);
delete_all(&n1);
}
You declared an object in main() with automatic storage duration as the first node of the list:
node n1;
You may not destroy it using the delete operator.
Using your approach of the list implementation, you could define the function delete_all() the following way:
void delete_all(node* first)
{
if ( first != nullptr )
{
while ( first->next != nullptr )
{
node *temp = first->next;
first->next = temp->next;
delete temp;
}
}
}
But, it will be much better if initially in main(), you declared a pointer to a node. In this case, you will need to update the functions.
Your implementation of delete_all() is fine, but you are passing it a pointer to a node instance that was not created with new, so delete'ing that node is undefined behavior. ALL of your node instances should be created dynamically, including the 1st node.
As such, your add() function should be updated to not blindly return without creating a new node instance if first is initially NULL. You should instead update the caller's node* pointer to point at the new node that was created.
Also, writout() has undefined behavior if first is NULL, because you are unconditionally accessing first->next whether first is NULL or not.
With that said, try something more like this instead:
#include <iostream>
using namespace std;
struct node {
string name = "n1";
node* prev = nullptr;
node* next = nullptr;
};
node* add(node* &first, string name) {
if (!first) {
first = new node{name};
return first;
}
else {
node *prev = first;
while (prev->next) {
prev = prev->next;
}
prev->next = new node{name, prev};
return prev->next;
}
}
/* alternatively:
node* add(node* &first, string name) {
node **nowy = &first, *prev = nullptr;
while (*nowy) {
prev = *nowy;
nowy = &(prev->next);
}
*nowy = new node{name, prev};
return *nowy;
}
*/
void writeout(node* first) {
if (!first) {
cout << "first = NULL";
}
else {
do {
cout << first->name;
first = first->next;
if (first) cout << '\n';
}
while (first);
}
}
void delete_all(node* first) {
node* temp;
while (first) {
temp = first->next;
delete first;
first = temp;
}
}
int main()
{
node* n1 = nullptr;
add(n1, "n2");
add(n1, "n3");
writeout(n1);
delete_all(n1);
}
Alternatively:
...
node* add(node* first, string name) {
if (!first) {
return new node{name};
}
else {
while (first->next) {
first = first->next;
}
first->next = new node{name, first};
return first->next;
}
}
/* alternatively
node* add(node* first, string name) {
// same as node** further above ...
}
*/
...
int main()
{
node* n1 = add(nullptr, "n2");
add(n1, "n3");
...
delete_all(n1);
}
I am tasked with implementing a new class function called bool List::largest_value(int &largest) within a given class List. The instruction is:
If the list is not empty, put the largest value in the largest
parameter and return true. If the list is empty, return false.
My question is, how do I find the largest value within a parameter?
Here is what I have so far for bool List::largest_value(int &largest):
// Fill in the functions at the bottom of this file
//
#include <iostream>
#include <climits>
using namespace std;
#include "list.h"
// on some machines member variables are not automatically initialized to 0
List::List()
{
m_head = NULL;
}
// delete all Nodes in the list
// since they are dynamically allocated using new, they won't go away
// automatically when the list is deleted
// Rule of thumb: destructor deletes all memory created by member functions
List::~List()
{
while (m_head)
{
Node *tmp = m_head;
m_head = m_head->m_next;
delete tmp;
}
}
// always insert at the front of the list
// Note: this works even in the SPECIAL CASE that the list is empty
void List::insert(int value)
{
m_head = new Node(value, m_head);
}
// iterate through all the Nodes in the list and print each Node
void List::print()
{
for (Node *ptr = m_head; ptr; ptr = ptr->m_next)
{
cout << ptr->m_value << endl;
}
}
void List::compare(int target, int &less_than, int &equal, int &greater_than)
{
Node *temp = m_head;
less_than = 0;
equal = 0;
greater_than = 0;
while(temp != NULL)
{
if(temp->m_value > target)
{
greater_than++;
}
else if(temp->m_value < target)
{
less_than++;
}
else if(temp->m_value == target)
{
equal++;
}
temp = temp-> m_next;
}
}
bool List::largest_value(int &largest)
{
Node *temp = m_head;
largest = INT_MIN;
if(temp == NULL)
{
return false;
}
while(temp != NULL)
{
if(temp->m_value > largest)
{
largest = temp->m_value;
}
temp = temp->m_next;
}
return true;
}
Here is the given class List:
class List
{
public:
List();
~List();
void insert(int value); // insert at beginning of list
void print(); // print all values in the list
void compare(int target, int &less_than, int &equal, int &greater_than);
bool largest_value(int &largest);
private:
class Node
{
public:
Node(int value, Node *next)
{m_value = value; m_next = next;}
int m_value;
Node *m_next;
};
Node *m_head;
};
Main.cpp:
#include <iostream>
using namespace std;
#include "list.h"
int main()
{
List list;
int value;
// read values and insert them into list
while (cin >> value)
{
list.insert(value);
}
int largest;
bool result = list.largest_value(largest);
if (result == false)
{
cout << "empty list" << endl;
return 1;
}
else
{
cout << "The largest value you entered is: " << largest << endl;
}
}
My code compiles and runs, however I keep receiving the output empty list. I honestly have no idea what I need to change in my bool List::largest_value(int &largest)function. I am still very new to linked lists. Any help would be appreciated
I'm trying to implement my own version of a linked list for learning. I have the following code. The reverseList function works correctly and if I print it inside that function it is good.
However, when I leave the function and then call the print method I get the the first value and then nothing (null). I'm guessing when I get out of the function it brings me back to the original first ([99]) element which is now actually the last element. So my print method outputs the element sees null is the next and ends.
Or I was thinking the changes I was making in the function were somehow only in that function's scope even though I passed a pointer, but that doesn't make sense because if that's the case then I should have all the original data still.
struct ListNode
{
int value;
ListNode* next = NULL;
};
void insertRecList(ListNode* list, int value)
{
if(list->next == NULL)
{
ListNode* end = new ListNode;
end->value = value;
list->next = end;
}
else
insertRecList(list->next, value);
}
void printList(ListNode* list)
{
std::cout << list->value << std::endl;
while(list->next != NULL)
{
list = list->next;
std::cout << list->value << std::endl;
}
}
void reverseList(ListNode* list)
{
ListNode* next;
ListNode* prev = NULL;
ListNode* cur = list;
while(cur != NULL)
{
if(cur->next == NULL)
{
cur->next = prev;
break;
}
else
{
next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
}
list = cur;
std::cout << cur->value << " list:" << list->value << std::endl;
}
void testLinkedList()
{
srand(time(NULL));
ListNode nodes;
nodes.value = 99;
int val;
for(int i = 0; i < 5; i++)
{
val = rand() % 30 + 1;
insertRecList(&nodes, i);
//insertList(&nodes, val);
}
printList(&nodes);
reverseList(&nodes);
printList(&nodes);
}
int main()
{
testLinkedList();
return 0;
}
Appreciative of any help you guys can give me,
Thanks!
Update:
By passing the ListNode *list to reverseList, you create a copy of your pointer which point to the same address with nodes. Inside the function, you assign list to the updated cur pointer but the copy will be destroyed at the end. list still points to the same address as before passing to reverseList but its next has changed.
I have modified your code a little bit:
#include <cstdlib>
#include <iostream>
struct ListNode
{
int value;
ListNode* next = nullptr;
};
void insertRecList(ListNode* list, int value)
{
if(list->next == nullptr)
{
ListNode* end = new ListNode;
end->value = value;
list->next = end;
}
else
insertRecList(list->next, value);
}
void printList(ListNode* list)
{
std::cout << list->value << std::endl;
while(list->next != nullptr)
{
list = list->next;
std::cout << list->value << std::endl;
}
}
void reverseList(ListNode** list)
{
ListNode* cur = *list;
ListNode* next = cur->next;
ListNode* prev = nullptr;
while(cur != nullptr)
{
next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
*list = prev;
}
void cleanNodes(ListNode *list) {
// clean goes here
}
void testLinkedList()
{
srand(time(nullptr));
ListNode *nodes = new ListNode();
nodes->value = 99;
int val;
for(int i = 0; i < 5; i++)
{
val = rand() % 30 + 1;
insertRecList(nodes, i);
//insertList(&nodes, val);
}
printList(nodes);
reverseList(&nodes);
printList(nodes);
cleanNodes(nodes);
}
int main()
{
testLinkedList();
return 0;
}
Try to compile with: -std=gnu++11
You don't change nodes in reverseList you're just changing list you're just changing a pointer on your struct which is a temporary object so physically nodes steel the same and pointed on the same first element which now has next attribute pointing on Null so the result of printList is correct. You need to work with pointers e.g.
#include <iostream>
#include <cstdlib>
struct ListNode
{
int value;
ListNode* next = NULL;
~ListNode(){
if(this->next)
delete this->next;
}
};
void insertRecList(ListNode* list, int value)
{
if(list->next == NULL)
{
ListNode* end = new ListNode;
end->value = value;
list->next = end;
}
else
insertRecList(list->next, value);
}
void printList(ListNode* list)
{
std::cout << list->value << std::endl;
while(list->next != NULL)
{
list = list->next;
std::cout << list->value << std::endl;
}
}
ListNode * reverseList(ListNode* list)
{
ListNode* next;
ListNode* prev = NULL;
ListNode* cur = list;
while(cur != NULL)
{
if(cur->next == NULL)
{
cur->next = prev;
break;
}
else
{
next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
}
std::cout << cur->value << " list:" << list->value << std::endl;
return cur;
}
void testLinkedList()
{
srand(time(NULL));
ListNode * nodes = new ListNode;
nodes->value = 99;
int val;
for(int i = 0; i < 5; i++)
{
val = rand() % 30 + 1;
insertRecList(nodes, i);
//insertList(&nodes, val);
}
printList(nodes);
nodes = reverseList(nodes);
printList(nodes);
delete nodes;
}
int main()
{
testLinkedList();
return 0;
}
Also, don't forget to delete object created dynamically
Reversing a linked list is not a fundamental operation. It does not belong among the basis operations of your class. It is easier (and safer) to implement it in terms of your other operations. Roughly:
Create an empty list.
While the first list is not empty, remove a node from the front of the first list and insert it into the front of the second list.
The second list is now the reverse of the original.
Hi I am trying to make a doubly linked list to store individual numbers as nodes of a doubly linked list and then add them together and print them out for a homework assignment. I am having a lot of trouble getting this to work and have traced my problem to my add node functions as they don't update the pointers correctly. For example on the AddToFront() function I can't understand how I can get the prev pointer to work and point to the node behind it.
I can't use the STL and have to implement the LL myself in case anyone is wondering. Thanks!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <iostream>
using namespace std;
/////// PART A
template <class T>
class List {
private:
struct Node {
T data;
Node *next;
Node *prev;
};
Node *front, *current, *rear;
public:
List();
~List();
void AddtoFront (T newthing);
void AddtoRear (T newthing);
bool FirstItem (T & item);
bool LastItem (T & item);
bool NextItem (T & item);
bool PrevItem (T & item);
};
template <class T>
List<T>::List() {
front = NULL; current = NULL; rear = NULL;
}
template <class T>
List<T>::~List() {
}
template <class T>
void List<T>::AddtoFront (T newthing) {
if (front == NULL) {
Node *temp;
temp = new Node;
temp->data = newthing;
temp->next = front;
temp->prev = NULL;
front = temp;
} else {
Node *temp;
temp = new Node;
front->prev = temp;
temp->data = newthing;
temp->next = front;
temp->prev = NULL;
front = temp;
}
}
template <class T>
void List<T>::AddtoRear (T newthing) {
if (rear == NULL) {
Node *temp;
temp = new Node;
temp->data = newthing;
temp->prev = rear;
temp->next = NULL;
rear = temp;
} else {
Node *temp;
temp = new Node;
rear->next = temp;
temp->data = newthing;
temp->prev = rear;
temp->next = NULL;
rear = temp;
}
}
template <class T>
bool List<T>::FirstItem (T & item) {
if (front == NULL) { return false; }
current = front;
item = front->data;
return true;
}
template <class T>
bool List<T>::LastItem (T & item) {
if (rear == NULL) { return false; }
current = rear;
item = rear->data;
return true;
}
template <class T>
bool List<T>::NextItem (T & item) {
if (current != NULL) current = current->next;
if (current == NULL) { return false; }
item = current->data;
return true;
}
template <class T>
bool List<T>::PrevItem (T & item) {
if (current == NULL) { return false; }
if (current->prev != NULL) current = current->prev;
item = current->data;
return true;
}
/////// PART B
class BigNumber {
private:
//complete here...
//include here a List of integers, or shorts etc
List<int>L;
public:
//complete here...
//what methods do you need?
//e.g., ReadFromString, PrintBigNumber, AddBigNumbers
BigNumber();
~BigNumber();
void ReadFromString(char * decstring);
void PrintBigNumber();
void AddBigNumbers(BigNumber B1, BigNumber B2);
};
BigNumber::BigNumber(){
// anything here?
}
BigNumber::~BigNumber(){
//you can keep that empty
}
void BigNumber::ReadFromString (char * decstring ) {
//read a string, adding a new node per digit of the decimal string
// To translate 'digits' to integers: myinteger=decstring[index]-48
//You need to use the AddtoFront()
int temp;
for (unsigned i=0; i < strlen(decstring); ++i) {
//cin >> decstring[i];
temp = decstring[i]-48;
//L.AddtoFront(temp);
L.AddtoRear(temp);
//cout <<"Number added!" <<endl;
}
}
void BigNumber::PrintBigNumber () {
//complete here, print the list (i.e., use FirstItem() and NextItem() )
int val;
if (L.FirstItem(val)) {
cout << val;
} else {
cout << "print failed";
}
//if (L.FirstItem(val)) { cout << "true-first";} else { cout <<"false-first";};
//if (L.LastItem(val)) { cout << "true";} else { cout <<"false";};
//L.FirstItem(val);
//cout << val;
/*while (L.PrevItem(val)){
cout << val;
//cout <<"Print error!Value not here.";
}*/
}
void BigNumber::AddBigNumbers(BigNumber B1,BigNumber B2){
//complete here.
//use FirstItem(), NextItem() and AddNode()
//to add two big numbers, what do you have to do? Be careful about the carry
//Remember to add the last carry, the resulting number can have one more digit than B1 or B2
}
/////// PART C
BigNumber B1, B2, RES;
int main (int argc, char ** argv) {
//use command line arguments
if(argc!=3){printf("usage: executable number1 number2\n");exit(0);}
B1.ReadFromString(argv[1]);
B2.ReadFromString(argv[2]);
//print
cout << endl<< "Add the following numbers " << endl;
B1.PrintBigNumber();
cout << " + ";
B2.PrintBigNumber();
cout << " = " << endl;
//compute the addition
RES.AddBigNumbers(B1,B2);
//print the result
RES.PrintBigNumber();
cout << endl;
return 0;
}
EDIT: I added in a line each in AddToFront() and AddToRear(). Is this on the right track?
AddtoFront needs to also update the prev pointer for front. That is, you're currently doing
temp -> front <-> rest_of_list
where it needs to be
temp <-> front <-> rest_of_list.
Also, you might notice that the two branches of your if statement in AddtoFront are identical... :)
I am trying to build my own implementation of a linked list in C++. My code is compiling but apparently there is some issue with my pointers referring to invalid memory addresses.
Here is my implementation:
#include <iostream>
#include <string>
using namespace std;
class Node
{
private:
string _car;
Node* nextNode;
public:
void setCar(string car)
{
_car = car;
}
string getCar()
{
return _car;
}
void setNextNode(Node* node)
{
nextNode = node;
}
Node* getNextNode()
{
return nextNode;
}
};
Node* findLast(Node* node)
{
Node* nodeOut = NULL;
while (node->getNextNode() != NULL)
{
nodeOut = node->getNextNode();
}
return nodeOut;
}
string toString(Node* node)
{
string output = "";
while (node->getNextNode() != NULL)
{
output += node->getCar() + " ";
node = node->getNextNode();
}
return output;
}
int main()
{
char xit;
//ser head node to NULL
Node* headNode = NULL;
//create node 1
Node* node1 = new Node();
node1->setCar("Mercedes");
//create node 2
Node* node2 = new Node();
node2->setCar("BMW");
//set node links
headNode->setNextNode(node1);
node1->setNextNode(node1);
node2->setNextNode(node2);
headNode = node1;
Node* lastNode = findLast(headNode);
lastNode->setNextNode(NULL);
cout << toString(headNode) << endl;
//pause console
cin >> xit;
}
You need to relook at your code.
headNode = node1;
This assignment should be done before accesing any member function of the instance headNode.
Intially you have assigned NULL to this pointer.
After creating node1 you are setting to headNode that is invalid instance. This is the cause of crash.
Be ensure with your objective and then try to implement do some rough work on paper , make some diagram that way you would be more clear that what you are exactly trying to achive.
why setNextNode ??? i don't undeerstand what you wanted to achieve. be clear first.
As per my undertanding this code should be implemented like below..
#include <iostream>
#include <string>
using namespace std;
class Node
{
private:
string _car;
Node* nextNode;
public:
void setCar(string car)
{
_car = car;
}
string getCar()
{
return _car;
}
void setNextNode(Node* node)
{
nextNode = node;
}
Node* getNextNode()
{
return nextNode;
}
};
Node* findLast(Node* node)
{
Node* nodeOut = node->getNextNode();
while ( nodeOut->getNextNode()!= NULL)
{
nodeOut = nodeOut->getNextNode();
}
return nodeOut;
}
string toString(Node* node)
{
string output = "";
while (node != NULL)
{
output += node->getCar() + " ";
node = node->getNextNode();
}
return output;
}
int main()
{
char xit;
//ser head node to NULL
Node* headNode = NULL;
//create node 1
Node* node1 = new Node();
node1->setCar("Mercedes");
node1->setNextNode(NULL);//Make null to each next node pointer
headNode = node1; //assign the node1 as headNode
//create node 2
Node* node2 = new Node();
node2->setCar("BMW");
node2->setNextNode(NULL);
//set node links
node1->setNextNode(node2);
Node* lastNode = findLast(headNode);
lastNode->setNextNode(NULL);
cout << toString(headNode) << endl;
//pause console
cin >> xit;
}
Hope it would be useful for the beginner who implement ing the linklist in c++.
Reread this:
node1->setNextNode(node1);
node2->setNextNode(node2);
...and think about what you're doing here.
If you're going to write linked-list code, I'd advise at least looking at the interface for std::list. Right now, you're interface is at such a low level that you'd be at least as well off just manipulating pointers directly.
The cause of your actual error is:
headNode->setNextNode(node1);
headNode is still set to NULL, thus you're dereferencing a NULL pointer. As noted by Jerry, you're also calling having nodes point to themselves, which is not what you want.
It would be cleaner if you took the car as a constructor parameter.
When you allocate a new Node, the pointer nextNode is not initialized, it's just random junk. You will need to explicitly set it to NULL (probably in a constructor for Node).
Also, I assume you know that the standard C++ library has a linked list built in and you're just doing this for learning ;-)
Thanks for all the suggestions, here is my final code after major cleanup:
// LinkedListProject.cpp : main project file.
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace System;
using namespace std;
class Node
{
public:
Node()
:_car(""), _nextNode(NULL)
{
}
void SetCar(string car)
{
_car = car;
}
string GetCar()
{
return _car;
}
void SetNextNode(Node *node)
{
_nextNode = node;
}
Node * GetNextNode()
{
return _nextNode;
}
private:
string _car;
Node *_nextNode;
};
string GetData();
Node * AddNode(Node *firstNode, Node *newNode);
Node * DeleteNode(Node *firstNode, string nodeData);
void PrintNodes(Node *firstNode);
int main(int argc, char *argv[])
{
string command = "";
string data = "";
Node *firstNode = NULL;
do
{
cout << "Enter command: ";
cin >> command;
if(command == "add")
{
data = GetData();
Node *newNode = new Node();
newNode->SetCar(data);
firstNode = AddNode(firstNode, newNode);
}
else if(command == "delete")
{
data = GetData();
firstNode = DeleteNode(firstNode, data);
}
else if(command == "print")
{
PrintNodes(firstNode);
}
} while(command != "stop");
return 0;
}
string GetData()
{
string data = "";
cout << "Enter data: ";
cin >> data;
return data;
}
Node * AddNode(Node *firstNode, Node *newNode)
{
//add new node to front of queue
newNode->SetNextNode(firstNode);
firstNode = newNode;
return firstNode;
}
Node * DeleteNode(Node *firstNode, string nodeData)
{
Node *currentNode = firstNode;
Node *nodeToDelete = NULL;
if (firstNode != NULL)
{
//check first node
if(firstNode->GetCar() == nodeData)
{
nodeToDelete = firstNode;
firstNode = firstNode->GetNextNode();
}
else //check other nodes
{
while (currentNode->GetNextNode() != NULL &&
currentNode->GetNextNode()->GetCar() != nodeData)
{
currentNode = currentNode->GetNextNode();
}
if (currentNode->GetNextNode() != NULL &&
currentNode->GetNextNode()->GetCar() == nodeData)
{
nodeToDelete = currentNode->GetNextNode();
currentNode->SetNextNode(currentNode->GetNextNode()->GetNextNode());
}
}
if(nodeToDelete != NULL)
{
delete nodeToDelete;
}
}
return firstNode;
}
void PrintNodes(Node *firstNode)
{
Node *currentNode = firstNode;
while(currentNode != NULL)
{
cout << currentNode->GetCar() << endl;
currentNode = currentNode->GetNextNode();
}
}