I want to write a function that adds an integer (passed as an argument to the function) to each item in the unordered linked list. Here is the complete program.
#include <iostream>
using namespace std;
//creates a node class
class Node {
//defines data, and next as a pointer.
private:
int data; //data in the beginning node
Node *next; //pointer to the next node
public:
Node(int initdata) {
data = initdata; //the initialized data is set as the head
next = NULL; //the next node is set as NULL, as there is no next node yet.
}
int getData() { //function that return data of a given node.
return data;
}
Node *getNext() { // pointer that gets the next node
return next;
}
void setData(int newData) { // sets data in node
data = newData;
}
void setNext(Node *newnext) {
next = newnext;
}
};
// creates unorderedlist that points to the head of the linked list
class UnorderedList {
public:
Node *head;
UnorderedList() { // makes the head node equal to null
head = NULL;
}
bool isEmpty() { // the head node is empty if it is null
return head == NULL;
}
void add(int item) { //cerates a "temp" pointer that adds the new node to the head of the list
Node *temp = new Node(item);
temp->setNext(head);
head = temp;
}
int size() { //cereates a "current" pointer that iterates through the list until it reaches null
Node *current = head;
int count = 0;
while (current != NULL) {
count++;
current = current->getNext();
}
return count;
}
// creates "current" pointer that iterates through the list
// untli it finds the item being searched for, and returns a boolean value
bool search(int item) {
Node *current = head;
while (current != NULL) {
if (current->getData() == item) {
return true;
} else {
current = current->getNext();
}
}
return false;
}
void addInteger(int item){
Node *current = head;
while (current != NULL) {
current->getData() = current->getData() + item;
}
}
// uses current and previous pointer to iterate through the lists
// finds the items that is searched for, and removes it
void remove(int item) {
Node *current = head;
Node *previous = NULL;
bool found = false;
while (!found) {
if (current->getData() == item) {
found = true;
} else {
previous = current;
current = current->getNext();
}
}
if (previous == NULL) {
head = current->getNext();
} else {
previous->setNext(current->getNext());
}
}
friend ostream& operator<<(ostream& os, const UnorderedList& ol);
};
ostream& operator<<(ostream& os, const UnorderedList& ol) {
Node *current = ol.head;
while (current != NULL) {
os<<current->getData()<<endl;
current = current->getNext();
}
return os;
}
int main() {
UnorderedList mylist;
mylist.add(1);
mylist.add(2);
mylist.add(3);
mylist.add(4);
mylist.add(5);
mylist.add(6);
cout<<"MY LIST: "<<endl<<mylist;
mylist.addInteger(5);
cout<<"=========================================================\n";
cout<<"After adding 5 to each element, the list now is\n";
cout<<"MY LIST: "<<endl<<mylist;
return 0;
}
Now the program shows an error in the following function from the program above regarding the assignment operation.
void addInteger(int item){
Node *current = head;
while (current != NULL) {
current->getData() = current->getData() + item;
}
}
How can I add a number to each element of the linked list?
Any help is appreciated.
You probably want something like the following:
current->setData(current->getData() + item);
Note that now you are retrieving a return value in the left-hand side, then trying to assign to it. This is what your compiler is telling you, presumably.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have a task where I need to design and implement a class template using singly-linked list:
template <typename Key, typename Info> class Sequence { // ... // implemented using a singly-linked list }
The second part of the task comes after the main implementation, which is to create a function 'shuffle' To test flexibility of the class template above.
template <typename Key, typename Info> Sequence<Key, Info> shuffle ( const Sequence<Key, Info> & source1, int startIndex1, int length1, const Sequence<Key, Info> & source2, int startIndex2, int length2)
The function template shuffle should produce a sequence from two input sequences by interleaving subsequences of lengths length1 and length2 respectively. The subsequences should start at positions startIndex1 and startIndex2 respectively and continue till the ends of source sequences.
Let’s have an example with sequences, where keys are presented with colours distinguishing the source sequences
RESULT = shuffle ( source1, 3, 3, source2, 1, 2)
I have so far implemented everything that is necessary for a class template using singly-linked list.
The only part I need help implementing is the shuffle function described above. here's my code so far:
#include <iostream>
using namespace std;
template < typename Key, typename Info > class Sequence;
template < typename Key, typename Info >
Sequence <Key, Info> operator+ (const Sequence < Key, Info > &a,
const Sequence < Key, Info > &b);
template < typename Key, typename Info > class Sequence
{
private:
struct Node
{
Key ID;
Info information;
Node *next;
};
Node *head; // it's a singly linked list, but requires both head & tail in order to use the insert before& after function
Node *tail;
int numberOfNode;
void removeAll () //because c++ does not remove anything automatically, needs to remove all
{
if (head == NULL)
return;
Node *NodeToDelete = head;
while (NodeToDelete != NULL)
{
head = head->next;
delete[]NodeToDelete;
delete NodeToDelete;
NodeToDelete = head; //now the first node of the list is gone, nodeToDelete is the second node
}
tail = NULL;
numberOfNode = 0;
};
void copyAll (const Sequence < Key, Info > &s)
{
head = NULL;
tail = NULL;
numberOfNode = 0;
if (s.head == NULL)
return;
Node *NodeToCopy = s.head;
while (NodeToCopy)
{
push_back (NodeToCopy->ID, NodeToCopy->information);
NodeToCopy = NodeToCopy->next;
}
};
public:
Sequence ()
{
head = NULL;
tail = NULL;
numberOfNode = 0;
}
~Sequence ()
{
removeAll ();
}
Sequence (const Sequence < Key, Info > &s)
{
copyAll (s);
}
Sequence & operator= (const Sequence < Key, Info > &s)
{
if (this == &s)
return *this;
removeAll ();
copyAll (s);
return *this;
}
bool operator== (const Sequence < Key, Info > &s) const
{
if (size() != s.size())
return false;
Node *NodeToCompare = s.head;
Node *comparedNode = head;
while (NodeToCompare != NULL)
{
if (comparedNode->ID == NodeToCompare->ID)
{
NodeToCompare = NodeToCompare->next;
comparedNode = comparedNode->next;
}
else
return false;
}
return true;
}
bool operator != (const Sequence < Key, Info > &s) const
{
//writing the interior of the function simply as a return value
//in the end, true& false values are outputted as 1/0, bool returns 1/0
return !(*this == s);
}
//+= operator processes and returns everything to the object itself
Sequence < Key, Info > &operator += (const Sequence < Key, Info > &s)
{
if (s.empty ())
return *this;
if (this == &s)
{
*this = *this + s;
return *this;
}
Node *NodeToCopy = s.head;
while (NodeToCopy != NULL)
{
push_back (NodeToCopy->ID, NodeToCopy->information);
NodeToCopy = NodeToCopy->next;
}
return *this;
}
//operator + can add multiple things at the same time. Doesn't necessarily need to obtain a sum
Sequence < Key, Info > &operator + (const Sequence < Key, Info > &a)
{
Node *temp = a.head;
while (temp != NULL)
{
push_back (temp->ID, temp->information);
temp = temp->next;
}
return *this;
}
void insertAfter (const Key &location, const Key & newID,
const Info & newInfo)
{
Node *NodeToAdd = new Node (newID, newInfo, NULL);
if (head == NULL)
{
head = NodeToAdd;
tail = head;
numberOfNode++;
return;
}
//We get the position of head from constructor, once we add sth there
Node *current = head; // looking for position location we will place new created Node
while (current->next != NULL && current->ID != location)
current = current->next;
//Connecting between the new node, and the second half of the node first, so that when splitting the link, the second half won't be lost
NodeToAdd->next = current->next;
//Now, disconnecting the link between the current node to the second half of the link, so the new node can be the only link that connect them 2.
current->next = NodeToAdd; // if we want to add to the end of the list we will need to set tail pointer correctly
if (!NodeToAdd->next)
tail = NodeToAdd;
numberOfNode++;
}
void insertBefore (const Key & location, const Key & newID,
const Info & newInfo)
{
Node *NodeToAdd = new Node (newID, newInfo, NULL);
Node *current = head;
Node *previous = NULL; // looking for position location we will place new created Node
while (current != NULL && current->ID != location)
{
previous = current;
current = current->next;
} // we want to add at the beginning or we want to add first Node
if (!previous)
{
NodeToAdd->next = head;
head = NodeToAdd;
if (!tail)
tail = head;
}
else
{
NodeToAdd->next = previous->next;
previous->next = NodeToAdd; // if we want to add to the end of the list we will need to set tail pointer correctly
if (!NodeToAdd->next)
tail = NodeToAdd;
}
numberOfNode++;
}
//add Node in the end of the list
void push_back (const Key & newID, const Info & newInfo)
{
Node *NodeToAdd = new Node ();
NodeToAdd->ID = newID;
NodeToAdd->information = newInfo;
NodeToAdd->next = NULL;
if (head == NULL)
{
head = NodeToAdd;
tail = head;
}
else
{
tail->next = NodeToAdd;
tail = tail->next;
}
numberOfNode++;
}
//add Node in front of the list
void push_front (const Key & newID, const Info & newInfo)
{
Node *NodeToAdd = new Node (newID, newInfo, head);
if (head == NULL)
{
head = NodeToAdd;
tail = head;
}
else
head = NodeToAdd;
numberOfNode++;
}
bool remove (const Key & location)
{
if (head == NULL)
return false;
Node *NodeToDelete = head;
Node *previous = NULL; // looking for position of Node to be deleted
while (NodeToDelete != NULL && NodeToDelete->ID != location)
{
previous = NodeToDelete;
NodeToDelete = NodeToDelete->next;
} // if Node is found
if (NodeToDelete)
{ // if we want to delete the first Node
if (!previous)
{
head = head->next;
delete NodeToDelete;
numberOfNode--;
if (size () == 0)
tail = NULL;
}
else
{
previous->next = NodeToDelete->next;
delete NodeToDelete;
numberOfNode--; // if we have deleted tail Node
if (!previous->next)
tail = previous;
}
return true;
} // Node not found
else
return false;
}
bool positionKey (int place) const
{
//head isn't empty, and the place is a valid value
if (head != NULL && place >= 0)
{
Node *temp = head;
int i = 0;
while (i < place && temp != NULL)
{
temp = temp->next;
++i;
}
if (temp != NULL)
return true;
}
return false;
}
Key & positionKeyAt (int place) const
{
Node *temp = head;
int i = 0;
while (i < place && temp != NULL)
{
temp = temp->next;
++i;
}
return temp->ID;
}
bool positionInfo (int place) const
{
if (head != NULL && place >= 0)
{
Node *temp = head;
int i = 0;
while (i < place && temp != NULL)
{
temp = temp->next;
++i;
}
if (temp != NULL)
return true;
}
return false;
}
Info & positionInfoAt (int place) const
{
Node *temp = head;
int i = 0;
while (i < place && temp != NULL)
{
temp = temp->next;
++i;
}
return temp->information;
}
void erase ()
{
removeAll ();
}
void printAll () const
{
Node *current = head;
cout << "Printing sequence!" << endl;
while (current != NULL)
{
if (current->next == NULL)
{
cout << "ID: " << current->ID;
cout << " Info: " << current->information << endl;
cout << "______END______" << endl;
}
else
{
cout << "ID: " << current->ID;
cout << " Info: " << current->information << endl;
}
current = current->next;
}
}
int size () const
{
return numberOfNode;
}
bool empty () const
{
return numberOfNode == 0;
}
};
template <typename Key, typename Info> Sequence<Key, Info>
shuffle ( const Sequence<Key, Info> & source1, int startIndex1, int length1,
const Sequence<Key, Info> & source2, int startIndex2, int length2){
//Here is where i need help
}
int main ()
{
Sequence <int, int>seq1;
Sequence <int, int>seq2;
return 0;
}
The interleaving is the easy part. Given two input sequences and an output sequence:
while ((inputSeq1 has content) or (inputSeq2 has content))
{
for (int i = 0; (inputSeq1 has content) && i < 3; i++)
{
remove item from inputSeq1
append to outputSeq
}
for (int i = 0; (inputSeq2 has content) && i < 2; i++)
{
remove item from inputSeq2
append to outputSeq
}
}
That's the basic idea. You don't say whether you should stop the interleaving if one of the lists runs out of items, so I assumed you wanted everything.
I am trying to implement the peek() function of a Stack class and have this issue where I cannot return the top object of the stack, but instead get an error. I have tried removing the & to the peek function and tried to set it to a const, but I still get errors. Would the issue be outside of this function? as I am not sure what else I can try to solve this problem.
Error:
LStack.h:55:28: error: cannot bind non-const lvalue reference of type ‘int&’
to
an rvalue of type ‘int’
return data.get_current();
LStack.h
#include "LinkedList.h"
#include <cstdlib>
#include <iostream>
template <typename T>
class LStack
{
public:
//mutator member functions
LStack(){}
~LStack(){}
void push(const T& obj) //insert obj at the top of the stack
{
data.add_to_head(obj);
numofstacks++;
}
T pop() //remove and return the top object from the stack, error if stack is empty
{
if (is_empty()){
std::cout << "Stack is empty";
}
else{
data.remove_from_head();
numofstacks--;
return data.get_current();
}
}
bool is_empty() const //return a boolean indicating whether the stack is empty
{
return (size() == 0);
}
//query member functions
int size() const //return the number of objects in the stack
{
return numofstacks;
}
//return a reference to the object at the top of the stack, NULL if the stack is empty, (also refered to as top())
T& peek()
{
if (is_empty()){
std::cout << "Stack is empty";
}
else{
//return top of the stack object
return data.get_current();
}
}
private:
LinkedList<T> data;
int used;
int numofstacks;
};
LinkedList.h
#include "Node.h"
#include <cstdlib>
#include <iostream>
template <typename T>
class LinkedList
{
public:
LinkedList() //constructor
{
head = NULL;
tail = NULL;
list_length=0;
}
~LinkedList()//destructor since we're creating the linked list on the heap
{
while (head != NULL)
{
remove_from_head();
}
tail = NULL;//not sure if in or out of while loop
}
LinkedList(T& item)
{
head = new Node<T>();
head->set_data(item);
tail = head;
list_length = 1;
}
void add_to_head(T item)
{
if (list_length == 0){ //if list is empty
head = new Node<T>();
head->set_data(item);
tail = head;
list_length = 1;
}
else //Else if list is not empty.. Insert node at the head
{
Node<T>* head_insert = new Node<T>();
head_insert->set_data(item);
head->set_prev(head_insert);
head_insert->set_next(head);
head = head_insert;
list_length++;
head_insert = NULL;
}
}
void add_to_tail(T item)
{
if (list_length == 0){
head = new Node<T>();
head->set_data(item);
tail = head;
list_length = 1;
}
else //insert node at tail
{
Node<T>* tail_insert = new Node<T>();
tail_insert->set_data(item);
tail->set_next(tail_insert);
tail_insert->set_prev(tail);
tail = tail_insert;
list_length++;
tail_insert = NULL;
}
}
void remove_from_head()
{
if (list_length == 0){
return;
}
else if (list_length == 1){
delete head;
head = NULL;
tail = NULL;
list_length--;
return;
}
else
{
Node<T>* temp_head = head;
head = temp_head->get_next();
delete temp_head;
list_length--;
temp_head = NULL;
}
}
void remove_from_tail()
{
if (list_length == 0){
return;
}
else if (list_length == 1)
{
delete head;
head = NULL;
tail = NULL;
list_length--;
return;
}
else
{
Node<T>* temp_tail = tail;
tail = temp_tail->get_prev();
delete temp_tail;
list_length--;
temp_tail = NULL;
}
}
std::size_t size()
{
return list_length;
}
T get_current() // RESULTS IN SEG ERROR
{
return current->get_data();
}
void forward()
{
current = current->get_next();
}
void back()
{
current = current->get_prev();
}
void move_to_head()
{
current = head;
}
void move_to_tail()
{
current = tail;
}
private: //private members
Node<T>* head; //point to start of list
Node<T>* tail; //point to end of list
Node<T>* current; //optional - used to refer to a node in our list
std::size_t list_length;
};
Would the issue be outside of this function? as I am not sure what else I can try to solve this problem.
Using the following code below I am getting a "Redefinition of SortedLL" error.
So I removed "class SortedLL" from the header file below. But when I remove SortedLL from the header file then I can't declare a SortedLL in the main.cpp file.
So I am stuck. What am I missing?
Sorted Linked List header file
#ifndef SortedLinkedList_SortedLL_h
#define SortedLinkedList_SortedLL_h
struct Node {
int data;
struct Node * next;
};
class SortedLL {
public:
int find(int data);
bool remove(int data);
int size();
bool removeOdd();
bool add(int data);
private:
struct Node * pHead;
int length;
};
#endif
Sorted Linked List CPP file
#include <iostream>
#include "SortedLL.h"
class SortedLL {
private:
// searches the linked list linearly
int findLinear(int data, struct Node ** pPrev, struct Node ** pCurr){
// start at head of list
*pCurr = pHead;
*pPrev = NULL;
int index = 0;
while (*pCurr != NULL){
if ((*pCurr)->data == data){
// found
return index;
}
else {
*pPrev = *pCurr;
*pCurr = (*pCurr)->next;
index++;
}
}
return -1;
}
bool findInsertPointLinear(struct Node ** pPrev, struct Node ** pCurr, int data){
while (*pCurr != NULL){
// if current data is less then new data
if ((*pCurr)->data < data){
// store previous node
*pPrev = *pCurr;
// advance to next position
*pCurr = (*pCurr)->next;
}
// current value is >= new val
else {
// we found insertion point
break;
}
}
return true;
}
// returns the value at the index or NULL if no value exists
bool get(int index, int * val) {
// check if out of bounds
if (index < 0 || index > (length-1)) {
// out of bounds
return false;
}
struct Node * pCurr = pHead;
for (int i=0;i<=index;i++){
pCurr = pCurr->next;
}
if (val != NULL) {
*val = pCurr->data;
}
return true;
}
public:
bool add (int data) {
struct Node * pCurr = pHead;
struct Node * pPrev = NULL;
bool returnVal = true;
// if the list is empty
if (pHead == NULL){
// add the new node
pHead = (struct Node *)malloc(sizeof(struct Node));
pHead->data = data;
pHead->next = NULL;
// return success
length++;
return returnVal;
}
// the list is not empty, so find insertion point
if (findInsertPointLinear(&pPrev, &pCurr, data)){
// if inserting at the begininng of list
if (pPrev == NULL){
pPrev = (struct Node *)malloc(sizeof(struct Node));
if (pPrev != NULL) {
pPrev->data = data;
pPrev->next = pCurr;
// keep track of head pointer
pHead = pPrev;
}
else {
// failed to allocate memory
returnVal = false;
}
}
// if inserting at end of list
else if (pCurr == NULL && pPrev !=NULL) {
pCurr = (struct Node *)malloc(sizeof(struct Node));
if (pCurr != NULL){
pCurr->data = data;
pPrev->next = pCurr;
pCurr->next = NULL;
}
else {
// failure to allocate memory
returnVal = false;
}
}
// if inserting in the middle of list
else {
pPrev->next = (struct Node *) malloc (sizeof(struct Node));
if (pPrev->next != NULL){
pPrev->next->data = data;
pPrev->next->next = pCurr;
}
else {
// failure to allocate memory
returnVal = false;
}
}
}
// increment size of list by 1
if (returnVal == true)
length++;
return returnVal;
}
// returns index of first occurrence of data or -1 if not found
int find(int data){
struct Node * pPrev = NULL;
struct Node * pCurr = NULL;
return findLinear(data, &pPrev, &pCurr);
}
bool remove(int data) {
// try to find data
struct Node * pPrev = NULL;
struct Node * pCurr = NULL;
int removeIndex = findLinear(data, &pPrev, &pCurr);
bool returnVal = false;
// if found
if (removeIndex != -1){
// remove node
return false;
}
// if removing at the head
if (removeIndex == 0){
if (pCurr != NULL){
pHead = pCurr->next;
free(pCurr);
pCurr = NULL;
returnVal = true;
}
else {
printf("trying to remove an element that does not exist\n");
}
}
// if removing at the end
else if (removeIndex == (length-1)){
if (pCurr != NULL) {
free(pCurr);
pCurr = NULL;
if (pPrev != NULL){
pPrev->next = NULL;
}
returnVal = true;
}
else {
printf("trying to remove an element that does not exist\n");
}
}
// removing somewhere in the middle
else {
if (pPrev != NULL && pCurr != NULL){
struct Node * temp = pCurr->next;
free(pCurr);
pCurr = NULL;
pPrev->next = temp;
returnVal = true;
}
// something is wrong
else {
printf("attempting to remove an element from middle but either previous or curr element is NULL\n");
}
}
return returnVal;
}
int size(){
return length;
}
bool removeOdd(){
struct Node * pCurr = pHead;
struct Node * pPrev = NULL;
// iterate over list
while (pCurr != NULL){
// if current data element is odd
if (pCurr->data %2 != 0){
// remove it
// removing at head
if (pCurr == pHead){
pHead = pHead->next;
free(pCurr);
pCurr = pHead;
}
// if removing at the end
else if (pCurr->next == NULL){
free(pCurr);
pCurr = NULL;
pPrev->next = NULL;
}
// removing somewhere in the middle
else {
struct Node * temp = pCurr->next;
free(pCurr);
pPrev->next = temp;
// advance pCurr to next node
pCurr = temp;
}
}
// if current data element even
else {
pPrev = pCurr;
pCurr = pCurr->next;
}
}
return true;
}
}SortedLL;
As # PaulMcKenzie points out, you've defined the class SortedLL in both your header and your .cpp file. What you want in the .cpp is just the method definitions. Something like:
int SortedLL ::findLinear(int data, struct Node ** pPrev, struct Node ** pCurr) {
...
}
I've gone through a bunch of threads trying to understand what is going on exactly with linked lists and bubblesort, and I think I get the bulk of it.
Right now my program is simply crashing when I get to the sort function and I am not sure why. Hopefully another set of eyes will see what I do not.
Any help is greatly appreciated.
DoublyList.h:
#include "listNode.h"
#ifndef DOUBLYLIST_H
#define DOUBLYLIST_H
template <typename T>
class DoublyList
{
public:
DoublyList();
~DoublyList();
void addFront(T d);
void addBack(T d);
T removeFront();
T removeBack();
T peak();
bool isEmpty();
int getSize();
void printList();
void sortList();
private:
ListNode<T> *front;
ListNode<T> *back;
int numOfElements;
};
template <typename T>
DoublyList<T>::DoublyList(){
front = NULL;
back = NULL;
numOfElements = 0;
}
template <typename T>
DoublyList<T>::~DoublyList(){
if(numOfElements!=0){
ListNode<T> *current;
current = front;
while (current != back)
{
ListNode<T> *temp = current;
current = current->next;
temp->next = NULL;
temp->prev = NULL;
delete temp;
numOfElements--;
}
//at this point current = back, now delete it
current->next = NULL;
current->prev = NULL;
delete current;
numOfElements--;
}
//this is a safeguard if you create a LL and then delete it without doing anything to it
else{
cout<<"deleted empty LL"<<endl;
delete front;
delete back;
}
}
template <typename T>
void DoublyList<T>::addFront(T d)
{
ListNode<T> *node = new ListNode<T>();
node->data = d;
if (isEmpty()){
back = node;
}
else{
front->prev = node;
}
node->next = front;
front = node;
++numOfElements;
}
template <typename T>
T DoublyList<T>::removeFront()
{
if (isEmpty()){
return T();
}
else
{
ListNode<T>* temp = front;
if (front->next == 0){
back = 0;
}
else
{
front->next->prev = 0;
}
front = front->next;
temp->next = 0;
T theData = temp->data;
delete temp;
--numOfElements;
return theData;
}
}
template <typename T>
void DoublyList<T>::addBack(T d)
{
ListNode<T> *node = new ListNode<T>();
node->data = d;
if (isEmpty()){
front = node;
}
else{
back->next = node;
}
node->prev = back;
back = node;
++numOfElements;
}
template <typename T>
T DoublyList<T>::removeBack()
{
if (isEmpty()) {
return T();
}
else
{
ListNode<T>* temp;
temp = back;
if (back->prev == 0){
front = 0;
}
else{
back->prev->next = 0;
}
back = back->prev;
temp->prev = 0;
T theData = temp->data;
delete temp;
--numOfElements;
return theData;
}
}
template <typename T>
T DoublyList<T>::peak()
{
if (isEmpty()) {
return T();
}
return front->data;
}
template <typename T>
int DoublyList<T>::getSize(){
return numOfElements;
}
template <typename T>
bool DoublyList<T>::isEmpty(){
if(numOfElements == 0){
return true;
}
else{
return false;
}
}
template <typename T>
void DoublyList<T>::printList(){
if(numOfElements!=0){
ListNode<T> *current = front;
while(current!=back)
{
cout<<current->data<<endl;
current = current->next;
}
cout<<back->data<<endl;
}
else{
cout<<"list is empty"<<endl;
}
}
template <typename T>
void DoublyList<T>::sortList(){
int size = getSize();
ListNode<T> *current;
ListNode<T> *dummy;
ListNode<T> *next;
if(current == NULL) return;
if(current -> next == NULL) return;
int swapped = 1;
while(swapped){
swapped = 0; //last pass unless there is a swap
while(current -> next != NULL){
if(current-> data < current -> next -> data){
swapped = 1; //swap, will need to re-enter while loop
//actual number swap
dummy -> data = current -> data;
current -> data = current -> next -> data;
current -> next -> data = dummy -> data;
}
current = current -> next;
}
}
}
#endif
listNode.h:
#include <iostream>
#ifndef LISTNODE_H
#define LISTNODE_H
using namespace std;
template <typename T>
class ListNode
{
public:
T data;//the data that we will store
ListNode();
ListNode(int d);
~ListNode();
ListNode *next;//int and ptr and the member variables
ListNode *prev;
};
template <typename T>
ListNode<T>::ListNode(int d){
data = d;
next = NULL;
prev = NULL;
}
template <typename T>
ListNode<T>::ListNode(){}
template <typename T>
ListNode<T>::~ListNode(){
delete next;
delete prev;
cout<<"deleted Node"<<endl;
}
#endif
testList.cpp
#include <iostream>
#include "doublyList.h"
#include "genericQueue.h"
int main(){
DoublyList<int> testQueue;
testQueue.addBack(3);
testQueue.addBack(5);
testQueue.addBack(2);
testQueue.addBack(10);
testQueue.addBack(1);
cout << "Before Sort: " << endl;
testQueue.printList();
cout << "After Sort: " << endl;
testQueue.sortList();
testQueue.printList();
}
The erors I could find so far are:
Your default ListNode() constructor doesn't null the next and prev pointers.
In void DoublyList<T>::sortList() you don't initialize dummy, so it just points into nowhere. Actually there is no reason to use a node list at all, you can just directly use a variable of type T.
You don't initialize current in the same function and you actually should reset current to e.g. front at the beginning of each outer loop.
You don't use next at all (and don't need to), so just remove it.
To sum it up, this is what void DoublyList<T>::sortList() could look like:
template <typename T>
void DoublyList<T>::sortList(){
int size = getSize();
ListNode<T> *current=front;
T dummy;
if (current == NULL) return;
if (current->next == NULL) return;
int swapped = 1;
while (swapped){
current = front;
swapped = 0; //last pass unless there is a swap
while (current->next != NULL){
if (current->data < current->next->data){
swapped = 1; //swap, will need to re-enter while loop
//actual number swap
dummy = current->data;
current->data = current->next->data;
current->next->data = dummy;
}
current = current->next;
}
}
}
and this is my suggestion for the ListNode constructor.
template <typename T>
ListNode<T>::ListNode() :
next(nullptr),
prev(nullptr),
data{}
{}
Besides that, I also agree with DaveB that swapping pointers is the approach you should actually use.
To start with you need to initialize current in your sort function,
current = first;
template <typename T>
void DoublyList<T>::sortList(){
ListNode<T> *current;
ListNode<T> *next;
T tmp;
current = front;
if(current == NULL) return;
if(current -> next == NULL) return;
int swapped = 1;
while(swapped){
swapped = 0; //last pass unless there is a swap
while(current->next != nullptr){
if(current->data < current->next->data){
swapped = 1; //swap, will need to re-enter while loop
//actual number swap
tmp = current->data;
current->data = current->next->data;
current->next->data = tmp;
}
current = current -> next;
}
if (swapped) // go back to start of list for next pass
current = front;
}
}