Print a linkedlist - c++

Given the name of a node, this function should search the linked list; if its found inside, then return a pointer that points to that node, otherwise return null. Note: I am certain I have written this function successfully.
// getNode
Node *LinkedList::getNode(string name)
{
Node *temp = head;
while (temp != NULL)
{
if (temp->name.compare(name) == 0)
return temp;
temp = temp->next;
}
return NULL;
}
Given a node, this function prints: teamName(winScore-loseScore) on screen. Examples: UCLA(25-13) or Texas A&M(31-25). Note: I am sure I have written this function successfully.
// printNode
void LinkedList::printNode(Node *node)
{
if (node == NULL)
return;
else {
cout << node->name << "(" << node->winScore;
cout << "-" << node->loseScore << ")";
}
}
Given a team name, this function is supposed to print all the nodes in its adjacency list one-by-one in the following format (NOTE: the following is just one example!) This is where I think I am wrong.
Missouri University beat: New Mexico(52-23), Salisbury (48-31), Virginia (34-9)
void LinkedList::printList(string name)
{
if (head == NULL)
cout << "\n Empty list" << endl;
else {
Node *temp = head;
while (temp != NULL)
{
cout << temp->name << " beat: " << temp->name << endl; // Is this right?
temp = temp->next;
}
}
}

I'm guessing that this is close to what you want:
void LinkedList::printList(string name)
{
// find the node for the name you supply
// (or else I don't understand why 'name' is supplied to this function)
Node *temp = getNode(name);
if (temp) { // node with name found
if (temp->next) { // there's at least one adjacent node
cout << temp->name << " beat: ";
while ((temp = temp->next) != nullptr) {
printNode(temp);
if (temp->next) cout << ", ";
};
cout << "\n";
} else { // no adjacent nodes
cout << temp->name << " did not beat anyone\n";
}
}
}

Related

C++ Sorted Doubly Linked List: Problems inserting in middle of list

below is my current in-progress code converting a singly linked to a doubly linked list. I haven't touched the delete function yet. I've gotten insert in empty list, end of list, and beginning of list apparently working.
However nodes inserting in the middle seemingly fail to create a link to the previous node. My debugging lines I inserted seem to show both the n->next and n-> prev with the correct memory address, but when I go to reverseprint, any nodes inserted in the middle are missed and the links are gone. Where am I going wrong in regards to this?
Code below:
#include <iostream>
#include <string>
using namespace std;
// define a node for storage and linking
class node {
public:
string name;
node *next;
node *prev;
};
class linkedList {
public:
linkedList() :top(NULL) {}
bool empty() { return top == NULL; }
node *getTop() { return top; }
node *getEnd() { return end; }
void setTop(node *n) { top = n; }
void setEnd(node *p) { end = p; }
void add(string);
int menu();
void remove(string);
~linkedList();
void reversePrint();
friend ostream& operator << (ostream&, const linkedList&); // default output is in-order print.
private:
node *top;
node *end;
};
void main() {
linkedList l;
cout << l.empty() << endl;
int option = 0;
string s;
bool go = true;
while (go) {
option = l.menu();
switch (option) {
case 1: cout << "enter a name: "; cin >> s; l.add(s); break;
case 2: cout << "enter name to be deleted: "; cin >> s; l.remove(s); break;
case 3: cout << l; break;
//case 4: cout << "can not be done with a singly linked list" << endl;
case 4: l.reversePrint(); break;
case 5: cout << "exiting" << endl; go = false; break;
}
}
system("pause");
}
void linkedList::remove(string s) {
bool found = false;
node *curr = getTop(), *prev = NULL;
while (curr != NULL) {
// match found, delete
if (curr->name == s) {
found = true;
// found at top
if (prev == NULL) {
node *temp = getTop();
setTop(curr->next);
delete(temp);
// found in list - not top
}
else {
prev->next = curr->next;
delete(curr);
}
}
// not found, advance pointers
if (!found) {
prev = curr;
curr = curr->next;
}
// found, exit loop
else curr = NULL;
}
if (found)cout << "Deleted " << s << endl;
else cout << s << " Not Found " << endl;
}
void linkedList::add(string s) {
node *n = new node();
n->name = s;
n->next = NULL;
n->prev = NULL;
// take care of empty list case
if (empty()) {
top = n;
end = n;
// take care of node belongs at beginning case
}
else if (getTop()->name > s) {
n->next = getTop();
n->prev = NULL;
setTop(n);
node *temp;
temp = n->next;
temp->prev = n;
// take care of inorder and end insert
}
else {
// insert in order case
node *curr = getTop(), *prev = curr;
while (curr != NULL) {
if (curr->name > s)break;
prev = curr;
curr = curr->next;
}
if (curr != NULL) { // search found insert point
n->next = curr;
cout << n->name << " " << n << " prev " << prev << " " << prev->name << endl;
n->prev = prev;
prev->next = n;
cout << "n->prev is: " << n->prev << " " << n->prev->name << endl;
cout << "n->next is: " << n->next << " " << n->next->name << endl;
}
// take care of end of list insertion
else if (curr == NULL) {// search did not find insert point
prev->next = n;
n->prev = prev;
cout << "n->prev is: " << n->prev << " " << n->prev->name << endl;
setEnd(n);
}
}
}
ostream& operator << (ostream& os, const linkedList& ll) {
//linkedList x = ll; // put this in and the code blows up - why?
node *n = ll.top;
if (n == NULL)cout << "List is empty." << endl;
else
while (n != NULL) {
os << n->name << endl;
os << n << endl;
if (n->next != NULL) {
os << "next is " << n->next << endl;
}
n = n->next;
}
return os;
}
void linkedList::reversePrint() {
node *n = end;
if (n == NULL)cout << "List is empty." << endl;
else
while (n != NULL) {
//cout << n->name << endl;
cout << "memory address of " << n->name << " is " << n << endl;
if (n->prev != NULL) {
cout << "prev is " << n->prev << endl;
}
n = n->prev;
}
return;
}
// return memory to heap
linkedList::~linkedList() {
cout << "~linkedList called." << endl;
node *curr = getTop(), *del;
while (curr != NULL) {
del = curr;
curr = curr->next;
delete(del);
}
}
int linkedList::menu() {
int choice = 0;
while (choice < 1 || choice > 5) {
cout << "\nEnter your choice" << endl;
cout << " 1. Add a name." << endl;
cout << " 2. Delete a name." << endl;
cout << " 3. Show list." << endl;
cout << " 4. Show reverse list. " << endl;
cout << " 5. EXIT " << endl;
cin >> choice;
}
return choice;
}
You are not setting the prev of the current in insertion into middle, just do:
n->next = curr;
curr->prev = n; // <-- this

How to delete a node in a linked list?

This is what I have so far, but it's not working. Basically skips to else if(cnode == preposition).
void LinkedList::Delete(Node *PrePosition) {
Node *cnode = head;
Node *pnode = NULL;
while (cnode != NULL) {
if (cnode->value != NULL) {
if (pnode == NULL) {
// if there is not previous node
head = cnode->next;
}
else if (cnode == PrePosition) {
// if there is previous node
cout << endl << "Deleting: " << cnode << endl;
pnode->next = cnode->next;
}
}
else {
// don't delete
pnode = cnode;
}
cnode = cnode->next;
}
}
1: Take the pointer from the previous node and point it to the next one after the one you want to delete
2: Delete the pointer from the previous node to the current node
3: Delete the pointer from the next node to the current node (if it is a doubly-linked list)
Three cases of delete in a singly linked-list:
delete the first node
void delete_first()
{
node *temp=new node;
temp=head;
head=head->next;
delete temp;
}
delete the last node
void delete_last()
{
node *current = new node;
node *previous = new node;
current=head;
while(current->next != NULL)
{
previous = current;
current = current->next;
}
tail = previous; // if you have a Node* tail member in your LinkedList
previous->next = NULL;
delete current;
}
delete at a particular position (your case)
void LinkedList::delete_position(int pos)
{
node *current=new node;
node *previous=new node;
current=head;
for(int i=1; i < pos; i++) //or i = 0; i < pos-1
{
previous=current;
current=current->next;
}
previous->next=current->next;
delete current;
}
^^ from codementor ^^
However if your function signature intends delete_node(Node* nodeToDelete) [PrePosition is not a good name in this case] and you want delete the node passed to the function without knowing its position in the list we can modify delete_position() like so:
void LinkedList::delete_node(Node* nodeToDelete)
{
node *current= head;
node *previous= nullptr;
if (head == nodeToDelete){
head = nodeToDelete->next;
delete nodeToDelete;
return
}//else
while(current != nodeToDelete)
{
previous = current;
current = current->next
}
previous->next = current->next;
delete nodeToDelete;
}
Also in your original code, if it's skipping the line you mentioned, pnode is always null when cnode has a non-null value in it.
Here are the full code
class SportShoe {
private:
struct nodeSport {
int ShoeID;
char BrandShoe[SIZE];
char TypeShoe[SIZE];
char ColourShoe[SIZE];
int SizeShoe;
float PriceShoe;
nodeSport *last;
};
nodeSport *first = NULL;
public:
int MenuSportShoe();
void AddSportShoe();
void DisplaySportShoe();
void DeleteSportShoe();
static void ExitSportShoe();
};
int SportShoe::MenuSportShoe() {
int OptionSportShoe = 0;
cout << endl;
cout << "Please select from the menu:" << endl;
cout << ":: 1 :: Add item to shoe list" << endl;
cout << ":: 2 :: Display shoes list" << endl;
cout << ":: 3 :: Delete item from the list" << endl;
cout << ":: 4 :: Back" << endl;
cout << "=>> ";
cin >> OptionSportShoe;
while (OptionSportShoe == 1){
AddSportShoe();
}
while (OptionSportShoe == 2){
DisplaySportShoe();
}
while (OptionSportShoe == 3){
DeleteSportShoe();
}
while (OptionSportShoe == 4){
ExitSportShoe();
}
return 0;
}
void SportShoe::AddSportShoe() {
nodeSport *tempShoe1, *tempShoe2;
tempShoe1 = new nodeSport;
cout << "Please enter the Shoe ID : (eg. 43210) " << endl;
cout << "=>> ";
cin >> tempShoe1->ShoeID;
cout << "Please enter the Shoe Brand: (eg. Adidas) " << endl;
cout << "=>> ";
cin.sync();
cin.getline(tempShoe1->BrandShoe,SIZE);
cout << "Please enter the Shoe Type : (eg. Running) " << endl;
cout << "=>> ";
cin.sync();
cin.getline(tempShoe1->TypeShoe,SIZE);
cout << "What is the Shoe Colour : (eg. Grey) " << endl;
cout << "=>> ";
cin.sync();
cin.getline(tempShoe1->ColourShoe,SIZE);
cout << "Please enter Shoe Size : (eg. 9) " << endl;
cout << "=>> ";
cin >> tempShoe1->SizeShoe;
cout << "Please enter the price of the Shoe : (eg. RM123.45) " << endl;
cout << "=>> RM ";
cin >> tempShoe1->PriceShoe;
tempShoe1->last = NULL;
if (first == NULL)
first = tempShoe1;
else
{
tempShoe2 = first;
while (tempShoe2->last != NULL)
tempShoe2 = tempShoe2->last;
tempShoe2->last = tempShoe1;
}
system("PAUSE");
MenuSportShoe();
}
void SportShoe::DisplaySportShoe() {
nodeSport *tempShoe1;
tempShoe1 = first;
while(tempShoe1){
cout << "ID : " << tempShoe1->ShoeID << endl;
cout << "Brand : " << tempShoe1->BrandShoe << endl;
cout << "Type : " << tempShoe1->TypeShoe << endl;
cout << "Colour : " << tempShoe1->ColourShoe << endl;
cout << "Size : " << tempShoe1->SizeShoe << endl;
cout << "Price : " << tempShoe1->PriceShoe << endl;
cout << endl;
tempShoe1 = tempShoe1->last;
}
system("PAUSE");
MenuSportShoe();
}
void SportShoe::DeleteSportShoe(){
nodeSport *tempShoe1, *tempShoe2;
int DataShoe;
tempShoe2 = tempShoe1 = first;
if(tempShoe1 == NULL)
{
cout << "\nList is empty!" << endl;
system("PAUSE");
MenuSportShoe();
}
while(tempShoe1 != NULL)
{
cout << "\nEnter the Shoes ID to be deleted: (eg. 123) ";
cin >> DataShoe;
tempShoe2 = tempShoe1;
tempShoe1 = tempShoe1->last;
if(DataShoe == tempShoe1-> ShoeID){
if(tempShoe1 == first) {
first = first->last;
cout << "\nData deleted ";
}
else{
tempShoe2->last = tempShoe1->last;
if(tempShoe1->last == NULL){
tempShoe2 = tempShoe2;
}
cout << "\nData deleted ";
}
delete(tempShoe1);
system("PAUSE");
MenuSportShoe();
}
else{
cout << "\nRecord not Found!!!" << endl;
system("PAUSE");
MenuSportShoe();
}
}
}
void SportShoe::ExitSportShoe(){
int sepatu;
cout << endl;
cout << "Please choose the option below."<<endl;
cout << ":: 1 :: Sport Shoe." << endl;
cout << ":: 2 :: Ladies High Heel." << endl;
cout << ":: 3 :: Exit" << endl;
cout << "=>> ";
cin >> sepatu;
while(sepatu == 1){
SportShoe listShoe;
listShoe.MenuSportShoe();
}
while(sepatu == 2){
HighHeel listShoe;
listShoe.MenuHighHeel();
}
while(sepatu == 3){
cout << "Thank you. Till we meet again."<< endl;
exit(1);
}
}
main() {
cout << "Hello! Welcome to MySepatu Online Shop administrator."<< endl;
cout << endl;
SportShoe::ExitSportShoe();
HighHeel::ExitHighHeel();
return 0;
}
public class linkedList {
int count = 0;
class Node {
int element;
Node next;
Node(int element) {
this.element = element;
}
}
Node head = null;
Node tail = null;
public void addNode(int Object) {
Node newNode = new Node(Object);
if (head == null) {
head = tail = newNode;
} else {
tail.next = newNode;
tail = newNode;
}
}
public void Display() {
Node current = head;
while (current!=null) {
System.out.println(current.element);
count ++;
current = current.next;
}
}
public void Length() {
System.out.println(count);
}
public void Remove(int node) {
Node curr = head;
while (curr!=null) { // looping the nodes
if (curr.element == node ) {
curr.element = curr.next.element;
curr = curr.next;
// To fix the Duplicates
while (curr!= tail) {
curr.element = curr.next.element;
curr = curr.next;
}
RemoveEnd();
break;
}
curr = curr.next;
}
}
public void RemoveEnd() {
Node current3 = head;
while (current3.next != tail) {
current3 = current3.next;
}
tail = current3;
tail.next = null;
}
}

sort strings in alphabetical order with linked lists in c++

I am doing an assignment of linked list of strings. Everything seems to work fine until I get to the sorting part. I am using classes as well. I already have 2 functions. The first one minimum(string) where it returns the string that would come first in alphabetical order.
This functions works fine. I also have a function remove(string) where it removes a node containing the given string from the linked list. It returns true if successful, otherwise false (if string was not in the list), in this case I have to erase the string returned by the minimum(string) function. The function I am having trouble is sort().
It wants me to define a StringNode pointer to be the head of a new list (the empty list) then I need a loop where I will call the functions of minimum(string) and remove(string). Inside the loop I also need to insert this node into the proper position in the new list (append it to the end). The old head pointer (now empty) must point to the new list.
I am very confused about this, so far I have this:
void StringList::sort()
{
StringNode *newList = new StringNode;
newList = NULL;
string mini;
bool removed;
while (newList->next != NULL)
{
StringNode *newList2 = new StringNode;
StringNode *p = head;
mini = minimum();
p->data = mini;
p->next = NULL;
newList2 = newList2->next;
newList2->next = p;
removed = remove(mini);
newList = newList2;
}
}
How I understand is: I need to create a new node which will be an empty list meaning newList->next = NULL; then on the loop I need to create another new node, and a pointer that will point to the head of new node inside the loop. I need to make the value given by the minimum be stored in the pointer p and the pointer to point back to the new node.
Any help will be greatly appreciated. Thanks!
Here is the hole program.
// StringList.cpp
#include <iomanip>
#include <iostream>
#include <sstream>
#include "StringList.h"
using namespace std;
//******************************************************************************
// StringList: creates an empty list
//******************************************************************************
StringList::StringList()
{
head = NULL;
}
//******************************************************************************
// StringList: deallocates all the nodes in StringList
//******************************************************************************
StringList::~StringList()
{
StringNode *p;
StringNode *n;
p = head;
while (p != NULL)
{
n = p->next;
delete p;
p = n;
}
}
//******************************************************************************
// count: returns the total number of nodes in the list.
//******************************************************************************
int StringList::count()
{
int count = 0;
StringNode *p;
p = head;
while ( p != NULL )
{
count++;
p = p->next;
}
return count;
}
//******************************************************************************
// add: adds a new node to the beginning of the list.
//******************************************************************************
void StringList::add(string movie)
{
StringNode *newNode = new StringNode;
newNode->data = movie;
newNode->next = head;
head = newNode;
}
//******************************************************************************
// remove: removes a node containing the string from linked list
// returns true if successful or false the string is not in the list
//******************************************************************************
bool StringList::remove(string movie)
{
StringNode *p = head;
StringNode *n = NULL;
while (p != NULL && p->data != movie )
{
n = p;
p = p->next;
if (p == NULL )
{
return false;
}
else if (p->data == movie)
{
n->next = p->next;
delete p;
return true;
}
}
}
//******************************************************************************
//display: Displays the strings in the list.
//******************************************************************************
void StringList::display()
{
StringNode *p;
p = head;
while (p != NULL)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
//******************************************************************************
//minimum: return the string in alphabetical order
//******************************************************************************
string StringList::minimum()
{
StringNode *p = head;
string minimum = p->data;
while (p->next != NULL)
{
p = p->next;
if(minimum > p->data)
{
minimum = p->data;
}
}
return minimum;
}
//******************************************************************************
//sort: will call the minimum function and remove function
//******************************************************************************
void StringList::sort()
{
StringNode* newhead; // create a new head pointer
string mini;
bool removed;
//adding the first node to the new list.
StringNode *newnode = new StringNode;
mini = minimum(); // get the minimum from the existing linked list
newnode->data = mini;
newnode->next = NULL;
newhead=newnode; //add the minimum node to the new list(with the newhead)
StringNode *p = newhead;
while (head != NULL) // loop should run until there's no node left in the original list
{
StringNode *newnode = new StringNode;
mini = minimum(); // get the minimum from the existing linked list
newnode->data = mini;
newnode->next = NULL;
p->next=newnode; //add the minimum node to the new list(with the newhead pointer)
removed = remove(mini);
p=p->next;
}
head=newhead; //finally change the head pointer, so that the head now points to sorted list.
}
// StringList.h
#ifndef STRINGLIST_H_INCLUDED
#define STRINGLIST_H_INCLUDED
#include <string>
using namespace std;
class StringList
{
private:
struct StringNode // the Nodes of the linked list
{
string data; // data is a string
StringNode *next; // points to next node in list
};
StringNode *head; // the head pointer
public:
StringList();
~StringList();
int count();
void add(string);
bool remove(string);
void display();
string minimum();
void sort();
};
#endif // STRINGLIST_H_INCLUDED
//Driver.cpp
#include<iostream>
#include<iomanip>
using namespace std;
#include "StringList.h"
int main()
{
//testing StringList
StringList slist;
string movie1 = "Star Wars";
string movie2 = "Fargo";
string movie3 = "Back to the Future";
string movie4 = "Titanic";
// Testing add/display/count
cout << "Testing add/display/count: " << endl;
cout << "count is: " << slist.count() << endl;
slist.add(movie1);
slist.display();
cout << "count is: " << slist.count() << endl;
slist.add(movie2);
slist.display();
cout << "count is: " << slist.count() << endl;
slist.add(movie3);
slist.add(movie4);
slist.display();
cout << "count is: " << slist.count() << endl;
// Testing remove
cout << endl;
cout << "Testing remove: " << endl;
bool delResult;
delResult = slist.remove(movie4);
cout << "remove result movie4 = " << boolalpha << delResult << endl;
delResult = slist.remove(movie3);
cout << "remove result movie3 = " << boolalpha << delResult << endl;
delResult = slist.remove("Not There");
cout << "remove result Not There = " << boolalpha << delResult << endl;
cout << "display after remove: " << endl;
slist.display();
cout << "count is: " << slist.count() << endl;
//Testing minimum
cout << endl;
cout << "Testing minimum: " << endl;
cout << "Test minimum 1: " << endl;
slist.display();
cout << "minimum: " << boolalpha << slist.minimum() << endl;
cout << "Test minimum 2: " << endl;
slist.add(movie4);
slist.display();
cout << "minimum: " << boolalpha << slist.minimum() << endl;
cout << "Test minimum 3: " << endl;
slist.add(movie3);
slist.display();
cout << "minimum: " << boolalpha << slist.minimum() << endl;
//Testing sort and display
cout << endl;
cout << "Testing sort/display: " << endl;
slist.sort();
slist.display();
cout << endl;
cout << "Testing sort/display after add: " << endl;
slist.add("Jurassic Park");
slist.display();
cout << "now sorted: " << endl;
slist.sort();
slist.display();
}
your remove function has small fault. You didn't take care of the possibility of removing the first node.
bool StringList::remove(string movie)
{
StringNode *p = head;
StringNode *n = NULL;
if(p->data==movie) //added this condition
{
head=head->next;
delete p;
return true;
}
while (p != NULL && p->data != movie )
{
n = p;
p = p->next;
if (p == NULL )
{
return false;
}
else if (p->data == movie)
{
n->next = p->next;
delete p;
return true;
}
}
}
final sort function. The objective is to sort the existing list by using the minimum and remove functions and get the new sorted list. You need to get minimum from the existing list and keep adding them at the end of the new list. And finally change the head pointer to point it to the new list.
The while loop should run until the existing list becomes empty.
void StringList::sort()
{
string mini;
bool removed;
//adding the first node to the new list.
StringNode *newnode1 = new StringNode;
mini = minimum(); // get the minimum from the existing linked list
newnode1->data = mini;
newnode1->next = NULL;
removed =remove(mini);
StringNode *p = newnode1;
while (head != NULL) // the loop should run until the original list is empty
{
StringNode *newnode = new StringNode;
mini = minimum(); // get the minimum from the existing linked list
newnode->data = mini;
newnode->next = NULL;
p->next=newnode; //add the minimum node to the new list
removed = remove(mini);
p=p->next;
}
head=newnode1; //finally change the head pointer, so that the head now points to sorted list.
}

C++ Priority Queue Class with Linked List

I am having two issues with my c++ code (The test file is below):
I can't seem to figure out why its not breaking out of the while loop, when running, its stuck on the loop "7 versus 325".
So it should go into the next node of temp, which would be null, and then jump into the section where it adds it to the end of the queue. But its just looping and looping.
My second issue is with the the function I have commented out, queue1.back, whenever that is ran, it just errors out and gives what appears to be the address, but the .front() function works just fine.
The Test File I am working with is like this:
89 Alex
325 Rob
72 Joy
91 Bob
using namespace std;
class Person
{
friend class Pqueue;
public:
int priority;
string name;
};
class PQueue
{
friend class Person;
private:
//Structure for my linked list.
typedef struct node {
Person data;
struct node *next;
}Node, *NodePtr;
Node *head, *tail;
public:
//Prototype Functions
PQueue(void); //Initializer function
bool empty(void); //Test if empty
int size(void); //Return size
void enqueue(Person *); //Insert Node
void dequeue(void); //Remove Node
Person* front(void); //Access Next Node
Person* back(void); //Access last node
};
PQueue::PQueue()
{
head = NULL;
tail = NULL;
}
bool PQueue::empty(){
return (head == NULL);
}
void PQueue::enqueue(Person *myPerson){
NodePtr np = (NodePtr) malloc(sizeof(Node));
np->data = *myPerson;
np->next = NULL;
if(empty())
{
cout << "Making into creating the first node, of the linked list" <<endl;
head = np;
tail = np;
}
else { //Queue has more the one node
Node* temp = head;
if(np->data.priority > temp->data.priority) //If the priority is greater then the rest.
{
head = temp; //Saving my head pointer
head->data = np->data; //Assigning new Data to the head pointer
head->next = temp; //Assigning the rest of the linked list back into head.
cout << "Making into creating the first node again, having to reassign." <<endl;
}
else{
//Searching where to place the node.
while(temp->data.priority > np->data.priority) //Searching if the next priority is higher then the passed.
{
cout << "Inside the while loop: " << np->data.priority << " versus "<<temp->data.priority <<endl;
if(temp->next == NULL)
break;
temp = temp->next;
}
if(temp->next == NULL && np->data.priority < temp->data.priority) //Inserting at the end.
{
cout << "Making into creating the last node" <<endl;
tail->next = np;
cout << "Passing the function of creating the last node" <<endl;
}
else //Inserting into the middle of the function.
{
cout << "Inserting in the middle of the queue" <<endl;
np->next = temp->next;
temp->next = np;
}
}
}
}
void PQueue::dequeue(){
if(empty()){
cout << "\nAttempt to remove from an empty list." << endl;
exit(1);
}
Person hold = head->data;
NodePtr temp = head;
head=head->next;
if (head == NULL) tail = NULL;
free(temp);
}
Person* PQueue::front(){
//Person &temp = head->next->data;
//Person &temp = head->data;
Person &temp = head->data;
return &temp;
}
Person* PQueue::back(){
if(empty()){
cout << "\nNo entries in list." << endl;
exit(1);
}
Person &temp = tail->data;
return &temp;
}
int main() {
cout << "Starting main" << endl;
PQueue queue1; //Creating my queue.
cout << "Created Queue" << endl;
Person tempPerson;
ifstream inFile;
inFile.open("/tmp/temp");
cout << "going into while loop" << endl;
while (inFile >> tempPerson.priority >> tempPerson.name){
cout << "The priority is " << tempPerson.priority << " the name is " << tempPerson.name <<endl;
queue1.enqueue(&tempPerson);
}
//Testing Section, trying to get .front and .back to work.
Person *testPerson;
testPerson = queue1.front();
cout << "The TEST priority is " << testPerson->priority << " the TEST name is " << testPerson->name <<endl;
/**
Person *tailPerson;
testPerson = queue1.back();
cout << "The TEST priority is " << tailPerson->priority << " the TEST name is " << tailPerson->name <<endl;
**/
queue1.dequeue();
queue1.dequeue();
queue1.dequeue();
return 0;
}
When you add a new head entry to a non-empty list, you're mistakenly setting the next pointer to point right back at the node it's in, rather than setting it to point at the rest of the linked list like you intended.
head = temp; //Saving my head pointer
head->next = temp; //Assigning the rest of the linked list back into head.

Templated Linked List giving wrong output when asked to print a node

I'm creating a database for school records for a project. I have a Student, Faculty, and Administrator class that all inherit things from a Person class. When I add the different objects to a Node, the information is stored in that Node (I see it via the debugger), however when I go to print a Node, I get
00266A88
instead of
Full Name: Reed
M Number: 999
Email:
and so on.
I'm just not sure what is causing the problem. Here is my method to print a node from the list:
template <typename T>
void TemplatedList<T>::printSpecific(int m_Number)
{
Node * Current = Head;
//If there is nothing in the list but the dummy head node, then return because there's nothing to print
if(Head->next == NULL)
{
cout << "Cannot print (M" << m_Number << "), NOT found!" << endl;
return;
}
else
Current = Current->next;
// While Current->next isn't equal to NULL, go through the list and see if the M-Numbers match. If they do, print the student and return
while(Current->next != NULL)
{
if(m_Number == Current->data->getM_Number())
{
cout << Current->data;
return;
}
else
{
Current = Current->next;
}
}
if(Current->next == NULL)
{
if(m_Number == Current->data->getM_Number())
{
cout << Current->data;
return;
}
else
{
cout << "Cannot print (M" <<m_Number << "), NOT found!" << endl;
return;
}
}
}
Here is the function to add one of the of the objects to the list:
template<typename T>
void TemplatedList<T>::addTemplatedList(T newAddition)
{
//Points to current node we're using
Node* Current = Head;
//Points to the node previous in the list to the current
Node* Previous = Head;
//Creates a new Node
Node* newNode = new Node;
//Assigns new Student information to new Node
newNode->data = newAddition;
// Check to see if the Head is only thing in the list. If it is, just place the new Node directly after the Head
if (Head->next == NULL)
{
Head->next = newNode;
newNode->next = NULL;
return;
}
else
{
while (Current->next != NULL)
{
if (newAddition->getM_Number() < Current->next->data->getM_Number())
{
newNode->next = Current->next;
Previous->next = newNode;
return;
}
else if (newAddition->getM_Number() == Current->next->data->getM_Number())
{
cout << "Person with M Number " << newAddition->getM_Number() << " not added because they are already in database." << endl;
delete newNode;
return;
}
Current = Current->next;
Previous = Previous->next;
}
if (Current->next == NULL)
{
Current->next = newNode;
newNode->next = NULL;
}
}
}
And finally here is how I'm calling the add function and creating a new object:
if (inputArray[0] == "A")
{
cout << "Adding Administrator: " << endl <<"\tFull Name:\t" << inputArray[1] << endl;
cout << "\tM Number:\t" << inputArray[2] << endl << "\tEmail Addr:\t" << inputArray[3] << endl << "\tTitle:\t " << inputArray[4] << endl;
Administrator *newAdmin = new Administrator;
istringstream stream (inputArray[2]);
int number;
stream >> number;
newAdmin->setAdmin(inputArray, number);
templatedList.addTemplatedList(newAdmin);
}
I would really appreciate and help that I can get because I'm just not sure what's happening or why it's giving me that incorrect output.
It looks like Node::data is a pointer to Administrator in this example. So when you do
cout << Current->data;
it merely outputs the pointer value. Assuming that you have implemented operator<< for the Administrator class, all you need to do is dereference:
cout << *Current->data;