Printing output with format (page x)-> in cpp - c++

Please provide the implementation of functions append, printList, and delete_evens as described in the comments. You will be dealing with a linked list of pages in which every node (page), is linked to its next and previous node (page) using next and prev pointers respectively. Please note the previous node of the first node (head) is NULL. In a similar way, the next of the last node will also be NULL.
The expected output is as follows:
Created PageList:
(page1)->(page2)->(page3)->(page4)->(page5)->(page6)->(page7)->(page8)->(page9)->(page10)->(page11)->(page12)->(page13)->(page14)->(page15)->(page16)->(page17)->(page18)->(page19)->(page20)->(page21)->(page22)->(page23)->(page24)->(page25)->(page26)->(page27)->(page28)->(page29)->(page30)->(page31)->(page32)->(page33)->(page34)->(page35)->(page36)->(page37)->(page38)->(page39)->(page40)->(page41)->(page42)->(page43)->(page44)->(page45)->(page46)->(page47)->(page48)->(page49)->(page50)->
Updated PageList:
(page1)->(page3)->(page5)->(page7)->(page9)->(page11)->(page13)->(page15)->(page17)->(page19)->(page21)->(page23)->(page25)->(page27)->(page29)->(page31)->(page33)->(page35)->(page37)->(page39)->(page41)->(page43)->(page45)->(page47)->(page49)->
The output I am getting is:
Created PageList:
(page)->1 (page)->2 (page)->3 (page)->4 (page)->5 (page)->6 (page)->7 (page)->8 (page)->9 (page)->10 (page)->11 (page)->12 (page)->13 (page)->14 (page)->15 (page)->16 (page)->17 (page)->18 (page)->19 (page)->20 (page)->21 (page)->22 (page)->23 (page)->24 (page)->25 (page)->26 (page)->27 (page)->28 (page)->29 (page)->30 (page)->31 (page)->32 (page)->33 (page)->34 (page)->35 (page)->36 (page)->37 (page)->38 (page)->39 (page)->40 (page)->41 (page)->42 (page)->43 (page)->44 (page)->45 (page)->46 (page)->47 (page)->48 (page)->49 (page)->50
Updated PageList:
(page)->1 (page)->3 (page)->5 (page)->7 (page)->9 (page)->11 (page)->13 (page)->15 (page)->17 (page)->19 (page)->21 (page)->23 (page)->25 (page)->27 (page)->29 (page)->31 (page)->33 (page)->35 (page)->37 (page)->39 (page)->41 (page)->43 (page)->45 (page)->47 (page)->49
My code is as follows:
#include <iostream>
#include <string>
using namespace std;
class Page {
public:
int page_number = 0;
string page_content = "";
Page *next = NULL;
Page *prev = NULL; // previous
};
class PageList {
public:
Page *head = NULL; // point to the first page
// append a page to the end of the list
void append(int page_number, string page_content) {
Page *first;
first = new Page();
first->page_content = page_content;
first->next = NULL;
first->prev = NULL;
first->page_number = page_number;
if (head == NULL) {
head = first;
} else {
Page *second = head;
while (second->next != NULL) {
second = second->next;
}
second->next = first;
}
}
// print all the elements of the list (pages) with the given format
void print list(Page *node, bool forward) {
while (node != NULL) {
cout << node->page_content << " ";
node = node->next;
}
cout << endl;
}
void delete_evens() { // delete the pages with even page_number
Page *first = head;
Page *q = NULL;
while (first != NULL) {
if (first->page_number % 2 == 0) {
if (q == NULL) {
head = first->next;
first = first->next;
} else {
q->next = first->next;
first->next = NULL;
first = q->next;
}
} else {
if (q == NULL) {
q = first;
first = first->next;
} else {
q = q->next;
first = first->next;
}
}
}
}
PageList(int pages) noexcept // consteructor
{
head = NULL;
for (int i = 1; i <= pages; i++) {
append(i, "(page" + to_string(i));
}
cout << "Created PageList:" << endl;
printList(head, true);
delete_evens();
cout << "Updated PageList:" << endl;
printList(head, true);
}
};
int main() {
PageList list(50);
return 0;
}
I believe that the error is somewhere in the line append(i, "(page" + to_string(i));
Can someone please help?

#include <iostream>
#include <string>
using namespace std;
// -------------------------------------------------------------------
class Page {
public:
int page_number = 0;
string page_content = "";
Page* next = NULL;
Page* prev = NULL;// previous
};
class PageList {
public:
Page* head=NULL; // point to the first page
// append a page to the end of the list
void append(int page_number, string page_content){
Page* first;
first=new Page();
first->page_content = page_content;
first->next=NULL;
first->prev=NULL;
first->page_number=page_number;
if(head==NULL) {
head=first;
}
else{
Page* second=head;
while(second->next != NULL) {
second=second->next;
}
second->next=first;
}
}
// print all the elements of the list (pages) with the given format
void printList(Page* node, bool forward) {
while(node != NULL) {
cout<<node->page_content<<""<<")->";;
node=node->next;
}
cout<<endl;
}
void delete_evens() // delete the pages with even page_number
{
Page* first = head;
Page* q=NULL;
while(first != NULL)
{
if(first->page_number % 2 == 0)
{
if(q==NULL)
{
head=first->next;
first=first->next;
}
else
{
q->next=first->next;
first->next=NULL;
first=q->next;
}
}
else
{
if(q==NULL)
{
q=first;
first=first->next;
}
else
{
q=q->next;
first=first->next;
}
}
}
}
PageList(int pages) noexcept // consteructor
{
head = NULL;
for (int i=1;i<=pages;i++){
append(i, "(page" + to_string(i));
}
cout<< "Created PageList:" << endl;
printList(head,true);
delete_evens();
cout<< "Updated PageList:" << endl;
printList(head,true);
}
};
// -------------------------------------------------------------------
int main()
{
PageList list(50);
return 0;
}

Related

Is there any way I could print these two linked lists side by side, instead of being on top of each other?

appendName is a function that inserts a string node at the end of the first linked list.
appendPrice is a function that inserts an integer node at the end of the second linked list.
printName is a function that prints the first linked list (linked list 1)
printPrice is a function that prints the second linked list (linked list 2)
struct nodeName
{
string Name;
nodeName *link;
};
void appendName(nodeName** head_name_ref, string new_Name)
{
nodeName* new_name_node = new nodeName();
nodeName *last = *head_name_ref;
new_name_node->Name = new_Name;
new_name_node->link = NULL;
if (*head_name_ref == NULL)
{
*head_name_ref = new_name_node;
return;
}
while (last->link != NULL)
{
last = last->link;
}
last->link = new_name_node;
return;
}
void printName(nodeName *node)
{
while (node != NULL)
{
cout<<" "<<node->Name<<endl;
node = node->link;
}
}
struct nodePrice
{
int Price;
nodePrice *link;
};
void appendPrice(nodePrice** head_ref, int new_Price)
{
nodePrice* new_node = new nodePrice();
nodePrice *last = *head_ref;
new_node->Price = new_Price;
new_node->link = NULL;
if (*head_ref == NULL)
{
*head_ref = new_node;
return;
}
while (last->link != NULL)
{
last = last->link;
}
last->link = new_node;
return;
}
void printPrice(nodePrice *node)
{
while (node != NULL)
{
cout<<" "<<node->Price<<endl;
node = node->link;
}
}
int main()
{
nodeName* headingNode1 = NULL;
appendName(&headingNode1, "item#1");
appendName(&headingNode1, "item#2");
nodePrice* pricingNode1 = NULL;
appendPrice(&pricingNode1, 6);
appendPrice(&pricingNode1, 14);
cout<<"Created Linked list is"<<endl;
printName(headingNode1);
printPrice(pricingNode1);
return 0;
}
Here is a picture of the output:
You can add another struct to include both lists:
struct nodeList
{
nodeName* names;
nodePrice* prices;
};
A new function to print the lists:
void printList(nodeList* list)
{
while (list->names != NULL && list->prices != NULL)
{
std::cout << " " << list->names->Name << std::endl;
list->names = list->names->link;
std::cout << " " << list->prices->Price << std::endl;
list->prices = list->prices->link;
}
}
And in the main function:
nodeList* list = new nodeList();
list->names = headingNode1;
list->prices = pricingNode1;
std::cout << "Created Linked list is" << std::endl;
//printName(headingNode1);
//printPrice(pricingNode1);
printList(list);
Output:
Created Linked list is
item#1
6
item#2
14
void printNameAndPrice(nodeName1 *node1, nodeName2 *node2){
while (node1 != NULL && node2 != NULL)
{
cout<<" "<<node1->Name<<endl;
cout<<" "<<node2->Price<<endl;
node1 = node1->link;
node2 = node2->link;
}}
Yes you can! you just want to add them in one method.
So the idea is to read them in parallel then update till the end.
Note: you can do the same in appending elements to the Linked List

How to sort doubly linked list in c++ without swapping data, only transferring (entries) nodes

I have got a problem in the sorting method of my linked list. I need to sort nodes in a doubly linked list by transferring links of nodes (entries of nodes). The method is stopped due to nullptr in the last node.
I do not know how to solve this problem. I tried a lot of variants, but no one was successful.
#include "DlinkedList.h"
// Node constructor
Node::Node()
{
this->rhetorician = NULL;
this->prev = NULL;
this->next = NULL;
}
// Node destructor
Node::~Node()
{
}
// List constructor
DlinkedList::DlinkedList()
{
this->length = 0;
this->head = NULL;
}
// Method for adding node at the end
void DlinkedList::appendNode(Rhetorician* rhetorician)
{
if (this->head == NULL) {
Node *new_node = new Node();
new_node->rhetorician = rhetorician;
this->head = new_node;
}
else {
Node *last_node = NULL;
for (Node *node_ptr = this->head; node_ptr != NULL; node_ptr = node_ptr->next)
{
last_node = node_ptr;
}
Node *new_node = new Node();
new_node->rhetorician = rhetorician;
last_node->next = new_node;
new_node->prev = last_node;
}
this->length++;
}
// Method for printing nodes
void DlinkedList::printNodes()
{
for (Node *node_cur = this->head; node_cur != NULL; node_cur = node_cur->next)
{
node_cur->rhetorician->printer();
cout << "---------------------------------------------------------------------------------------------------" << endl;
}
cout << endl << "##################################################################################################\n" << endl;
}
// Method for getting length
int DlinkedList::getLenght()
{
return this->length;
}
// Method for deleting node
void DlinkedList::remove(string name)
{
Node* logout_node = NULL;
for (Node* node_cur = this->head; node_cur != NULL; node_cur = node_cur->next)
{
if (node_cur->rhetorician->name == name)
{
logout_node = node_cur;
}
}
if (this->head != NULL || logout_node != NULL)
{
if (this->head == logout_node)
{
this->head = logout_node->next;
}
if (logout_node->next != NULL)
{
logout_node->next->prev = logout_node->prev;
}
if (logout_node->prev != NULL)
{
logout_node->prev->next = logout_node->next;
}
delete logout_node->rhetorician;
delete logout_node;
this->length--;
}
}
// Method for finding node
void DlinkedList::find(string name)
{
bool ver = false;
Node *n = NULL;
for (Node* node_cur = this->head; node_cur != NULL; node_cur = node_cur->next)
{
if (node_cur->rhetorician->name == name)
{
ver = true;
n = node_cur;
}
}
if (ver)
{
n->rhetorician->printer();
}
else
{
cout << "Rhetorician was not found!";
}
}
// Method for sorting nodes
void DlinkedList::sort()
{
int count = this->getLenght();
Node *tmp, *current;
int i, j;
for (i = 1; i < count; i++)
{
current = this->head;
for (j = 0; j <= count - i - 1; j++)
{
Node *before, *after;
if (current->rhetorician->coefficient > current->next->rhetorician->coefficient)
{
before = current->prev;
after = current->next;
if (before != NULL) {
before->next = after;
}
current->next = after->next;
current->prev = after;
after->next = current;
after->prev = before;
}
tmp = current;
current = current->next;
}
}
}
// List destructor
DlinkedList::~DlinkedList()
{
Node *next_node = NULL;
for (Node *node_cur = this->head; node_cur != NULL; node_cur = next_node)
{
next_node = node_cur->next;
delete node_cur->rhetorician;
delete node_cur;
}
this->head = NULL;
this->length = 0;
}
Main:
#include <iostream>
#include "DlinkedList.h"
#include <fstream>
#include <vector>
#include <sstream>
// Namespace
using namespace std;
// Parser of line to vector array
vector<string> split(string strToSplit, char delimeter)
{
stringstream ss(strToSplit);
string item;
vector<string> splittedStrings;
while (getline(ss, item, delimeter))
{
splittedStrings.push_back(item);
}
return splittedStrings;
}
// File loader
void read_file(const char *name, DlinkedList *list)
{
// Variable for loading line
string line;
{
// Create relation
ifstream file(name);
// Check if file exists
if (file)
{
// Check if file is empty
if (!(file.peek() == ifstream::traits_type::eof()))
{
// Read data from file and put into LinkedList
while (getline(file, line)) {
list->appendNode(new Rhetorician(split(line, ';')[0], split(line, ';')[1],
split(line, ';')[2], stoi(split(line, ';')[3])));
}
}
// Close file
file.close();
}
}
}
// Main method
int main()
{
// Create instance of doubly linked list
DlinkedList *list = new DlinkedList();
// Read file and push data into list
read_file("seznam_enumat.txt", list);
// Print all loaded rhetoricians behind added own one
cout << "\nAll rhetoricians from file:" << endl;
cout << "##################################################################################################\n" << endl;
list->printNodes();
// Append other rhetoricians
list->appendNode(new Rhetorician("Cain", "Foster", "Structural and molecular virology", 7));
list->appendNode(new Rhetorician("Stacy", "Algar", "Dept of microbiology and immunology", 5));
list->appendNode(new Rhetorician("Oded", "Philander", "Experimental plasma physics", 3));
list->appendNode(new Rhetorician("Shay", "Rimon", "Experimental plasma physics", 10));
// Sort rhetoricians in list
list->sort();
// Delete rhetorician by name
//list->remove("Stacy");
// Finder of rhetorician
cout << "\nFound rhetorician:" << endl;
cout << "##################################################################################################\n" << endl;
list->find("Shay");
// Print all sorted rhetoricians
cout << "\nAll rhetoricians:" << endl;
cout << "##################################################################################################\n" << endl;
list->printNodes();
// Destruct list
delete list;
// Check if user click any key
getchar();
return 0;
}
Rhetorician:
#include "Rhetorician.h"
Rhetorician::Rhetorician(string name, string surname, string contribution, int coefficient)
{
this->name = name;
this->surname = surname;
this->contribution = contribution;
this->coefficient = coefficient;
}
void Rhetorician::printer()
{
// Name
cout << "Name:" << endl;
cout << this->name << endl;
// Surname
cout << "Surname:" << endl;
cout << this->surname << endl;
// Contribution
cout << "Contribution:" << endl;
cout << this->contribution << endl;
// Coefficient
cout << "Coefficient:" << endl;
cout << this->coefficient << endl;
}
The main issue is in sort(). It is not handling the pointers correctly.
Take a short example, 3 -> 2 -> 1 and you will get it.
Here is the corrected code with unnecessary variables removed:
void DlinkedList::sort() {
int count = this->getLenght();
Node *current;
int i, j;
for (i = 1; i < count; i++) {
current = this->head;
for (j = 0; j <= count - i - 1; j++) {
Node *before, *after;
if (current->rhetorician->coefficient > current->next->rhetorician->coefficient) {
before = current->prev;
after = current->next;
if (before != nullptr) {
before->next = after;
} else {
// if before = null, it is the head node
this->head = after; // In case before pointer is null, after pointer should be the new head
}
current->next = after->next;
current->prev = after;
if (after->next != nullptr) {
after->next->prev = current; // prev pointer of after->next should be set to current.
}
after->next = current;
after->prev = before;
} else {
current = current->next; // Go to next node only if current->rhetorician->coefficient > current->next->rhetorician->coefficient condition is false.
}
}
}
}
The upwardly sorted list is working super but when I tried to sort the list downwardly only change the character > for < it is not working. Must be changed before node and after node?
// Zero or one element, no sort required.
if (this->head == NULL) return;
if (this->head->next == NULL) return;
// Force initial entry.
int swapped = 1;
while (swapped) {
// Flag as last time, then do one pass.
swapped = 0;
this->current = this->head;
while (this->current->next != NULL) {
Node *before, *after;
if (current->rhetorician->coefficient > current->next->rhetorician->coefficient) {
swapped = 1;
before = current->prev;
after = current->next;
if (before != NULL) {
before->next = after;
}
else {
// if before = null, it is the head node
this->head = after; // In case before pointer is null, after pointer should be the new head
}
current->next = after->next;
current->prev = after;
if (after->next != NULL) {
after->next->prev = current; // prev pointer of after->next should be set to current.
}
after->next = current;
after->prev = before;
}
current = current->next;
}
}// Zero or one element, no sort required.
if (this->head == NULL) return;
if (this->head->next == NULL) return;
// Force initial entry.
int swapped = 1;
while (swapped) {
// Flag as last time, then do one pass.
swapped = 0;
this->current = this->head;
while (this->current->next != NULL) {
Node *before, *after;
if (current->rhetorician->coefficient > current->next->rhetorician->coefficient) {
swapped = 1;
before = current->prev;
after = current->next;
if (before != NULL) {
before->next = after;
}
else {
// if before = null, it is the head node
this->head = after; // In case before pointer is null, after pointer should be the new head
}
current->next = after->next;
current->prev = after;
if (after->next != NULL) {
after->next->prev = current; // prev pointer of after->next should be set to current.
}
after->next = current;
after->prev = before;
}
current = current->next;
}
}

Alphabetically sorted links in doubly linked list

I've been having some trouble getting my program to insert given names along with their weights in a linked list which has a respective link for names and weights, which are both to be sorted in ascending / alphabetical order. The weight links work fine but I can't seem to identify what I'm getting wrong in my name linker. Any help would be greatly appreciated. The problem most likely lies in the insertName() private function.
#include <iostream>
#include <string>
using namespace std;
class DoublyLinkedList
{
public:
void insert(string name, double weight);
void printNameAsc();
void printWeightAsc();
private:
struct Node
{
string name;
double weight;
Node* nextName;
Node* nextWeight;
};
Node* nameHead = NULL;
Node* weightHead = NULL;
Node* newP = NULL;
void insertName();
void insertWeight();
};
void DoublyLinkedList::insert(string name, double weight)
{
// variable declaration
newP = new Node;
newP->name = name;
newP->weight = weight;
newP->nextName = NULL;
newP->nextWeight = NULL;
// empty first element check
if (nameHead == NULL && weightHead == NULL)
{
nameHead = newP;
weightHead = newP;
return;
}
// name and weight insertion
insertName();
insertWeight();
return;
}
void DoublyLinkedList::insertName()
{
Node* activeP = nameHead;
Node* prevP = NULL;
// traversing through name links
while (true)
{
if (activeP == NULL)
{
break;
}
if ((activeP->name).compare(newP->name))
{
break;
}
prevP = activeP;
activeP = activeP->nextName;
}
//insertion
newP->nextName = activeP;
if (activeP == nameHead)
{
nameHead = newP;
}
else
{
prevP->nextName = newP;
}
return;
}
void DoublyLinkedList::insertWeight()
{
Node* activeP = weightHead;
Node* prevP = NULL;
// traversing through weight links
while (true)
{
if (activeP == NULL)
{
break;
}
if (newP->weight < activeP->weight)
{
break;
}
prevP = activeP;
activeP = activeP->nextWeight;
}
//insertion
newP->nextWeight = activeP;
if (activeP == weightHead)
{
weightHead = newP;
}
else
{
prevP->nextWeight = newP;
}
return;
}
void DoublyLinkedList::printNameAsc()
{
Node* activeP = nameHead;
while (activeP != NULL)
{
cout << activeP->name << " " << activeP->weight << endl;
activeP = activeP->nextName;
}
return;
}
void DoublyLinkedList::printWeightAsc()
{
Node* activeP = weightHead;
while (activeP != NULL)
{
cout << activeP->name << " " << activeP->weight << endl;
activeP = activeP->nextWeight;
}
return;
}
int main()
{
DoublyLinkedList nameList;
nameList.insert("Michael", 275);
nameList.insert("Tom", 150);
nameList.insert("Abe", 200);
nameList.printNameAsc();
system("pause");
nameList.printWeightAsc();
system("pause");
return 0;
}
Pretty sure your problem is here:
if ((activeP->name).compare(newP->name) > 0)
{
break;
}
Looks like you're finding the insertion point with activeP. When activeP->name > newP->name, you want to stop searching.
if ((activeP->name).compare(newP->name))
Is invalid, this will evaluate true if activeP < newP (compare statement is -1) or activeP > newP (compare statement is 1), effectively only skipping people with the same names.
Remember, carried over from C, truth is defined as not falseness, which is defined as (!0)
Also, why not just pass a reference of newP to insertName() and insertWeight()? It's good practice to not leave (possibly dangling) pointers stored as member variables.

C++ circular linked list deletion, counts start at the next node

I have no idea how to delete in a circular link list. For example the head was B, so the list will go from "B, C, D, E, A". The first node will always pick a number from 1-5 which I keep reducing using the counter, so for example if "B" picked 3, the count will start unto it's next node which is "C" so counting from "C", we will have to eliminate "E", once "E" was eliminated.
The new head aka the picker will start unto the next node after the eliminated node, so the next set of nodes will become "A,B,C,D", this function must repeat until there is only 1 last standing node.
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include <string>
#include <ctime>
using namespace std;
/*
* Node Declaration
*/
struct node
{
string name;
struct node *next;
};
node *t, *head;
node *ex;
int paper;
int ctr = 5;
int num;
void create(string sname)
{
node *n = new node;
n->name = sname;
if (head == NULL)
{
head = n;
t = n;
}
else
{
t->next = n; // connects the nodes
t = t->next; // moves the connecter to the t= last
}
t->next = head;
}
/*
* Deletion of element from the list
*/
void delete_element(string value)
{
}
//Display Circular Link List
void display()
{
node *temp = new node;
temp = head;
if ((head == NULL) && (t == NULL))
{
}
for (int j = 1; j <= 5; j++)
{
cout << temp->name << "\n";
temp = temp->next;
}
}
void firstpic()
{
srand(time(NULL));
paper = rand() % 5 + 1;
int fctr = 5;
bool p1 = 0, p2 = 0, p3 = 0, p4 = 0, p5 = 0;
if (paper == 1)
{
create("A");//1
fctr--;
}
else if (paper == 2)
{
create("B");//2
p2 = 1;
}
else if (paper == 3)
{
create("C");//2
p3 = 1;
}
else if (paper == 4)
{
create("D");//2
p4 = 1;
}
else if (paper == 5)
{
create("E");//2
p5 = 1;
}
if (p1)
{
create("B");
create("C");
create("D");
create("E");
}
else if (p2)
{
create("C");
create("D");
create("E");
create("A");
}
else if (p3)
{
create("D");
create("E");
create("A");
create("B");
}
else if (p4)
{
create("E");
create("A");
create("B");
create("D");
}
else if (p5)
{
create("A");
create("B");
create("C");
create("D");
}
}
void drawn()
{
node *holder = head;
ex = holder->next;
cout << holder->name << " has drawn: " <<num <<endl;
}
int main()
{
head == NULL;
t == NULL;
srand(time(NULL));
firstpic();
display();
num = rand() % ctr + 1;
drawn();
system("pause>nul");
return 0;
}
Here is something that may suit your needs:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <ctime>
using namespace std;
/*
* Node Declaration
*/
struct node
{
string name;
struct node *next;
};
node *tail, *head;
void addNode(string sname)
{
node *n = new node;
n->name = sname;
if (head == NULL) {
head = n;
tail = n;
} else {
tail->next = n; // connects the nodes
tail = tail->next; // moves the connecter to the t= last
}
tail->next = head;
}
/*
* Deletion of element from the list
*/
void removeNode(string value)
{
// no elements
if (head == NULL) {
return;
}
node *n = head;
node *prev = tail;
// 1 element
if(n == prev) {
if(n->name == value) {
delete n;
head = tail = NULL;
}
return;
}
bool found = false;
// search
do {
if(n->name == value) {
found = true;
break;
}
prev = n;
n = n->next;
} while (n != head);
// no such element
if(!found) {
return;
}
prev->next = n->next;
if(n == head) {
head = n->next;
} else if(n == tail) {
tail = prev;
}
delete n;
}
void displayList()
{
if (head == NULL) {
cout << "empty!" << endl;
return;
}
node *n = head;
do {
cout << n->name << "\n";
n = n->next;
} while (n != head);
cout << endl;
}
void createList()
{
const int count = 5;
std::string names[count] = {"A", "B", "C", "D", "E"};
int nameIndex = rand() % count;
for(int i = 0; i<count; ++i) {
nameIndex += 1;
nameIndex %= count;
addNode(names[nameIndex]);
}
}
int main()
{
srand(time(NULL));
head = NULL;
tail = NULL;
createList();
displayList();
removeNode("A");
displayList();
removeNode("A");
displayList();
removeNode("E");
displayList();
removeNode("B");
displayList();
removeNode("C");
displayList();
removeNode("D");
displayList();
system("pause>nul");
return 0;
}
Note that during node deletion you should take care of such cases as:
No elements case
Last 1 element to be deleted
Head deletion
Tail deletion
Also, never do things like you did in your firstpic() function: it is a painfull way to do it. drawn() function seems not to do anything that makes sence, but it is out of question's scope.

returning something from a linked list

Can anybody tell me why my main program is printing out 9460301 instead of 350?
I'm just trying to insert a struct as a single item into a linked list. The struct has atrributes x and y. I then wish to print out the x attribute of the struct in my linked list. I have a huge program written out, and I tried stripping it down on this post just to what's neccessary to view for this new issue that has arisen for me.
My chunk struct and Linkedlist class are as follows:
struct chunk{
int x;
int y;
};
template <class T>
class linkedList
{
public:
class node
{
public:
///node class attributes
T mPayload;
node* mNext;
///constructor
node(T toucan):mPayload(toucan),mNext(NULL)
{}
///destructor
~node()
{
///cascading delete
if(mNext)
delete mNext;
}
///node class methods
};
///linkedList class attributes
node* mStart;
///constructor
linkedList():mStart(NULL)
{}
///destructor
~linkedList()
{
///initializes the cascading delete.
if(mStart)
delete mStart;
}
///linkedList class methods
T mReturnT(int indx)
{
if(!mStart)
{
T emptyList;
return emptyList;
}
else
{
node* cur;
for(int i = 0; i<indx+1; i++)
{
if(cur->mNext == NULL)
{
cout << "Indx out of range. Deleting last item." << endl;
break;
}
cur = cur->mNext;
}
return cur->mPayload;
}
}
void mInsertHelper(node* blah, T data)
{
if(blah->mNext != NULL)
mInsertHelper(blah->mNext, data);
else
{
blah->mNext = new node(data);
blah->mNext->mNext = NULL;
}
}
void mInsert(T data)
{
if(mStart == NULL)
{
mStart = new node(data);
//mStart->mPayload = data;
}
else
mInsertHelper(mStart, data);
}
T mPop()
{
///Removes the last item in the list,
///and returns it.
if(!mStart)
return NULL;
else
{
node* cur = mStart;
while(cur->mNext)
{
cur = cur->mNext;
}
T var = cur->mPayload;
delete cur;
return var;
}
}
int mSize()
{
if(!mStart)
return 0;
else
{
node* cur = mStart;
int counter = 1;
while(cur->mNext)
{
cur = cur->mNext;
counter++;
}
delete cur;
return counter;
}
}
};
And my main.cpp:
int main()
{
chunk head;
head.x = 350;
head.y = 600;
linkedList<chunk> p1Snake;
p1Snake.mInsert(head);
cout<<p1Snake.mReturnT(0).x<<endl;
}
You never initialise cur before iterating through it.
node* cur; // <-- UNINITIALISED!
for(int i = 0; i<indx+1; i++)
{
if(cur->mNext == NULL)
{
cout << "Indx out of range. Deleting last item." << endl;
break;
}
cur = cur->mNext;
}
return cur->mPayload;
That first line should be:
node* cur = mStart;
And I think you should use indx instead of indx+1 in that loop... Unless you were using a dummy-head scheme, which you're not.
The logic inside the loop for detecting out-of-bounds is a bit wrong, also. How about revamping the whole thing:
node* cur = mStart;
while( cur && indx > 0 ) {
cur = cur->mNext;
indx--;
}
if( !cur ) {
cout << "Indx out of range." << endl;
return T();
}
return cur->mPayload;