Printing nodes from REAR to FRONT enters infinite loop - c++

I am trying to output the elements from each node starting from right (rear/tail) to left (head/front). However, my program enters an infinite loop that displays the same element over and over again. Despite its infinite loop, the function that I created DisplayFromLeftToRight() (found below the DisplayFromRightToLeft() function) works like a charm, but this doesnt...
void DisplayFromRightToLeft()
{
node *newnode = rear;
int num = 1;
while (newnode != NULL)
{
cout << "Node # " << num << ": " << newnode->data << endl;
newnode = newnode->previous;
num++;
}
return;
}
This is the working code for printing element from each node from LEFT to RIGHT..
void DisplayFromLeftToRight()
{
node *newnode = front;
int num = 1;
while (newnode != NULL)
{
cout << "Node # " << num << ": " << newnode->data << endl;
newnode = newnode->next;
num++;
}
return;
}
If you believe that my DisplayFromRightToLeft() function is correct, I assume that the problem is from the INSERT function, take a look:
void INSERT(int _data)
{
node *newnode = new node;
newnode->data = _data;
newnode->next = NULL;
newnode->previous = newnode;
rear = newnode;
node *index = new node;
index = front;
if (isEmpty())
front = newnode;
else
{
while (index->next != NULL)
{
index = index->next;
}
index->next = newnode;
}
}

Looks like INSERT always sets previous to a valid address, so your while (newnode != NULL) loop will never end, because it sets newnode = newnode->previous each time.
You are correct that the problem seems to be in your INSERT function, and/or any other code that determines what is in your list.
Your Display...() functions look OK as far as not looping, by themselves, but by making them rely on a while(someNode != NULL) loop, they are dependent on the assumption that the list data is well-formed. Specifically, the first node must have a previous pointer to NULL, and the last node must have a next pointer to NULL, or else one of those Display functions will loop until it finds a NULL.
Looking at the INSERT function, if you follow the steps, you will see that it assigns a new valid address to newnode, and then sets previous to that valid address, while next gets NULL, and it can assign next to something else. How would previous ever be NULL? Previous also points to the inserted node itself, which looks like any loop following previous is just going to keep looking at the same node.
Whenever working with linked lists that I implement, I always step through the code and diagram what is going on - on paper is best, rather than just imagination. Only draw things you actually have your code do. Otherwise, you are probably assuming the resulting list data is what you intended, and not what you've actually coded.

You should change:
newnode->previous = newnode;
To:
newnode->previous = rear;
Line:
newnode->previous = newnode;
has no sense. It is like saying that I am my own father.

Related

Improve my solution to basic C linked list management functions

I would appreciate some help relative to my code solution, which deals with linked list management in C. I'll already declare the only strange thing with my request: I am writing a C++ file, but I am actually mostly leveraging C resources (malloc(), free(), etc.); that said, given the basic code I provide, I am confident no one will have trouble with that.
I want to write a function to add elements to the end of the list and one to delete elements from it, that work in any edge case. Given my desire, the removal function was the one that I struggled the most with, but also the one that made me realize how little I am understanding pointers.
I will now share the code I produced, that should be working fine, but:
It can surely be greatly improved both in terms of clarity and performance
I think that showing it to the community will highlight many of the flaws present in my solution
// The plan is to create a linked list and to be able to add and delete its elements
#include <iostream>
using namespace std; // I can write output lines as cout << "Hi!", rather than std::cout < "Hi!"
#include <cstdlib> // needed for malloc() in C++
struct node {
int data;
node* nextPtr; //"struct node* nextPtr;" : This would be the syntax for plain old C: you always have to type the "struct" keyword
};
node* createElement(int data) {
node* newElemPtr = (node*)malloc(sizeof(node)); // the "(node*)" cast is required by C++, and is not used in C
newElemPtr->data = data;
newElemPtr->nextPtr = NULL;
return newElemPtr;
}
void appendElement(int data, node** head) { // Adds a new node at the end of the list
// I pass as argument a pointer to pointer (double pointer) to node, so that I can edit the head node
// if the list is empty, without having to return a new node pointer as head: my function indeed features
// "void" in its signature
node* elemPtr = NULL;
elemPtr = createElement(data); // elemPtr is a pointer to the new node
if (*head == NULL) {
*head = elemPtr;
}
else {
node* currPtr = *head; // currPtr is the temporary variable that visits each node of the linked list
while (currPtr->nextPtr != NULL)
currPtr = currPtr->nextPtr;
currPtr->nextPtr = elemPtr; // Set last element's nextPtr to "elem", i.e., a pointer to the new element
}
};
void removeElement(int data, node** head) { // Remove all the nodes whose data content matches the "data" argument
int presence_flag = 0; // Flag used to check whether the required data is present at all in the linked list
if (*head == NULL) {
return;
}
else {
node* currPtr = *head;
node* prevPtr = *head;
while (currPtr != NULL) {
// This is the case in which I find a node to delete (it matches the "data" query), and it is not the first of the list
if (data == currPtr->data && currPtr != *head) {
prevPtr->nextPtr = currPtr->nextPtr; // Link the node ahead of the one to delete with the one behind
free(currPtr);
currPtr = prevPtr; // In the next loop, I will resume the analysis from the previous node, which now points to an unvisited one
presence_flag = 1;
}
// This is the case in which I find a node to delete and it is the first of the list
else if (data == currPtr->data && currPtr == *head) {
// This is the case in which I have to delete the first node, but the list features other nodes
if (currPtr->nextPtr != NULL){
*head = currPtr->nextPtr; // Move *head forward
currPtr = *head; // Do the same with currPtr, in order not to break the while() loop
free(prevPtr); // As *head has already been re-assigned, I leverage prevPtr to delete the old *head
presence_flag = 1;
}
// This is the case in which I have to delete the first and only node of the list
else {
*head = NULL;
currPtr = *head;
presence_flag = 1;
}
}
// This is the case in which the current node does not match the queried "data" value
else{
prevPtr = currPtr; // Update prevPtr
currPtr = currPtr->nextPtr; // Move currPtr forward
}
}
}
if (presence_flag == 0)
cout << "There is not any node with value " << data << " in the linked list.\n\n";
// Q1: Am I causing any memory leak by using *head == NULL instead of free(*head)?
// Q2: Should I free() everythin before ending the main(), at least as a good practice?
// Q3: Is there a way to make this function by not using a double pointer as input and by also keeping "void" as return value?
// Of course, it should still work in the tricky edge case of the last element in the list that has to be deleted
};
void printLinkedList(node* head) { // Here I return nothing, so I can freely edit "head" (i.e., there is no need for a temporary pointer)
if (head == NULL) {
cout << "The linked list is empty.\n";
}
else {
int elemCounter = 0;
while (head != NULL) {
elemCounter += 1;
cout << "elem N. " << elemCounter << ": data value = " << head->data << "\n"; // head->data is equal to (*head).data
head = head->nextPtr;
}
}
};
int main(int argc, char* argv[])
{
//cout << "Size of a single node of the list = " << sizeof(node) << "\n";
// == 16. On a 64 bits machine, an int ("data") requires 4 bytes.
// The pointer requires 8 bytes; the remaining 4 bytes are padding
node* head = NULL;
appendElement(1, &head);
appendElement(2, &head);
appendElement(3, &head);
printLinkedList(head);
cout << "\nRemoving element with data value = 1...\n\n";
removeElement(1, &head);
printLinkedList(head);
cout << "\nRemoving element with data value = 2...\n\n";
removeElement(2, &head);
printLinkedList(head);
cout << "\nRemoving element with data value = 3...\n\n";
removeElement(3, &head);
printLinkedList(head);
cout << "\nRemoving element with data value = 4...\n\n";
removeElement(4, &head);
printLinkedList(head);
cout << "\nRemoving element with data value = 1...\n\n";
removeElement(1, &head);
printLinkedList(head);
cout << "\nRemoving element with data value = 2...\n\n";
removeElement(2, &head);
printLinkedList(head);
return 0;
}
As you can see from the comments embedded in the code, I have 3 doubts that captured my interest while coding the node removal function:
Q1: Am I causing any memory leak by using *head == NULL instead of free(*head)?
Q2: Should I free() everything before ending the main(), at least as a good practice?
Q3: Is there a way to make this function by not using a double pointer as input and by also keeping "void" as return value? Of course, it should still work in the tricky edge case of the last element in the list that has to be deleted
I hope that featuring these "additional" questions is something reasonable to put here, as maybe someone in the future may have the same doubts I had.
I know there are plenty of ready-to-copy-and-paste solutions for my task, but I think I can really learn this stuff if I see why my precise design choices are not optimal/wrong.
I thank everyone for the time spent reading this.
There are many duplicated code. Also the function should not output any message. It is the caller of the function that decides whether to output a message. So the function should have the return type bool if you are considering the program as a C++ program or bool or int if you are considering the program as a C program.
The function removeElement invokes undefined behavior because in its paths of execution you are not always resetting correctly values of the pointers currPtr and prevPtr after deleting a node.
For example after this code snippet
if (data == currPtr->data && currPtr != *head) {
prevPtr->nextPtr = currPtr->nextPtr; // Link the node ahead of the one to delete with the one behind
free(currPtr);
currPtr = prevPtr; // In the next loop, I will resume the analysis from the previous node, which now points to an unvisited one
presence_flag = 1;
}
prevPtr and currPtr will be equal each other.
I would define the function the following way
int removeElement( node **head, int data )
{
int deleted = 0;
while ( *head )
{
if ( ( *head )->data == data )
{
deleted = 1;
node *current = *head;
*head = ( *head )->next;
free( current );
}
else
{
head = &( *head )->next;
}
}
return deleted;
}
As for your question
Q3: Is there a way to make this function by not using a double pointer
as input and by also keeping "void" as return value? Of course, it
should still work in the tricky edge case of the last element in the
list that has to be deleted
then in C you can not achieve this. In C++ you can pass the pointer to the first node by reference. In C passing by reference means passing an object indirectly through a pointer to it. So in C you have to use a double pointer in such a case.
Of course just setting a pointer to NULL without freeing data pointed to by the pointer that was dynamically allocated produces a memory leak. And you should free all the allocated memory then it is not required any more.

How can I check each 3 elements of a singly linked list and then delete some of them?

So basically I have this assignment on my University that asks to make a sorted singly linked list and then make some methods on it. The one that I'm having trouble is: "create delete() function that checks the average of each triple elements and if it's lower than integer 'K' (which is a parameter of said function) deletes the first element of the triple or deletes second and last element of the triple if it's higher."
I already made a function/method that deletes a single element of the linked list.
void LinkedList::deleteElement(int a)
{
Node *temp = head;
Node *previousTemp = head;
while(temp != nullptr)
{
if(temp->value == a)
{
break;
}
else
{
previousTemp = temp;
temp = temp->next;
}
}
if(temp == nullptr)
{
cout << "Can't delete. Element not found." << endl;
}
else
{
cout << "\nDeleting element: " << temp->value << endl;
previousTemp->next = temp->next;
delete temp;
}
howMany--;
}
void Sznur::deleteTriple()
{
Node *first = head;
Node *second = first->next;
Node *third = second->next;
}
The task is written pretty hard to understand but for ex.:
int K=3
linkedList: 7,6,6,3,3,3,2,1,1,1,1
after running the function:
linkedList: 7,3,1,1,1,1
(7+6+6)/3 > K -> deletes 6 and 6
(3+3+3)/3 > K -> deltes second 3 and last 3
(2+1+1)/3 < K -> deletes 2
If the linkedList length is not dividable by 3 the last elements stay in their place.
Try something like this.
void tripleFunc(Node* head, int K)
{
Node* nodePtr = head; // nodePtr always points at the start of a new triple
while (true)
{
Node* first = nullptr;
Node* second = nullptr;
Node* third = nullptr;
first = nodePtr; // When taking the three elements out, remember to always check for a null pointer BEFORE accessing the element
if (first)
second = first->next;
if (second)
third = second->next;
if (third)
nodePtr = third->next; // Keep the nodePtr pointing at the start of the next triple
else
return; // Only happens if one or more of the previous ifs failed, which means that we don't have enough elements left for a full triple
if (calculateAverage(first, second, third) < K) // Make this function
{
deleteElement(first->value);
}
else
{
deleteElement(second->value);
deleteElement(third->value);
}
}
}
I haven't tested it though, so any possible bugs are left as an exercise to the reader to find and sort out. :)

Linked list C++ not saving when using mutator to update the head's next

I am new to C++ and working on setting up a linked list.
Why is the below code not updating the list's head's next. I get the following output
void addToList(int dataToAdd){
Node nodeToBeAdded(dataToAdd, NULL); //initilize the node we are going to add with the data that was given by the user
if(this->getHead() == NULL){
this->setHead(&nodeToBeAdded);
cout << "Added " << this->getHead()->getData() << " to the head of the list\n";
return;
}
//Calls this even after I set the heads next
else if(this->getHead()->getNext() == NULL){
cout<<"Test\n";
this->getHead()->setNext(&nodeToBeAdded);
}
//IT NEVER REACHES THIS
else{
cout<<"super test\n";
}
}
I get the following output
Added 3 to the head of the list
Test
Test
Thanks
From what I can see, your current output is correct and expected based on your current code. The major problem I see is that your addition code only goes 1-2 steps past the head of the list when finding a point to insert a new node. The general procedure you should be following is to walk down the list until you reach the end, and then add the new node there. Something like this:
void addToList(int dataToAdd) {
Node* curr = this->getHead();
Node nodeToBeAdded(dataToAdd, NULL);
// for an empty list assign the head and return
if (curr == NULL) {
this->setHead(&nodeToBeAdded);
cout << "Added " << this->getHead()->getData() << " to the head of the list\n";
return;
}
// otherwise walk down the list and insert the new node at the end
while (curr->getNext() != NULL) {
curr = curr->getNext();
}
curr->setNext(&nodeToBeAdded);
return;
}

Doubly linked list Core dump

Thanks in advance.
I am making a doubly linked list.
Everything was working fine, but I realized that when I added a new class node somewhere in the middle, the left pointer would still be pointing at the node previously before it (now two spaces away).
So I added a new node pointer on line 46.
Then on line 51 I told that node to now point to the new node.
So :
First I had new node temp off in space
Then I make pointer temp2 loop through the list
Lastly I tell temp3 to point to the node after temp2's node
After the function runs, the order should be temp2->temp->temp3
My main point: After I added line 51, my program core dumps(segmentation fault) and closes out.
How can I fix this? It only happens when I add something that isn't taking place of the head pointer.
void add(node *&head, node *&tail, node *&current)
{
node *temp = new node; //creates a pointer pointing to a new class node
cin >> temp->letter; // user input
current = head; // creates a pointer to point at the first node
while (current != NULL) // while list isn't empty
{
if (current->letter == temp->letter)
{ // letter already exists
cout << "DUPLICATE: " << temp->letter << endl << endl;
return;
}
else
{ // loop through list moving tail pointer to the end while checking for duplicates
tail = current;
current = current->right_link;
}
}
current = temp; // current = new added node
if (isEmpty(head))
{ // if first node
temp->left_link = NULL;
temp->right_link = NULL;
head = temp; // head and
tail = temp; // tail both point to first and only node.
}
else
{ // if new letter value is less than head value
if(temp->letter < head->letter)
{
temp->right_link = head; // node points (right) to head
temp->left_link = NULL; // left most node point to nothing.
head->left_link = temp; // head (currently the second node) points (left) to first node
head = temp; // head pointer moves to the first position
}
else
{ // if new node goes anywhere other than head
node *temp2 = head; // new node to cycle through list
while(temp2->right_link != NULL && temp2->right_link->letter < temp->letter)
{ // if temp2 points to a node and that node's value is less than temp node value
temp2 = temp2->right_link;
}
node *temp3 = temp2->right_link;
temp->right_link = temp2->right_link; // when temp2 stops looping, temp will point to
// the same node as temp2.
temp2->right_link = temp; // temp2's current node will point to temp, causing temp
// to be added into the list (after temp2)
temp3->left_link = temp; // point the node (after the newly inserted node) left to new node
temp->left_link = temp2; // connects the left pointer between temp and temp2
if(temp->right_link == NULL)
tail = temp;
}
}
cout << "ADDED : " << temp->letter << endl << endl;
}
if temp2->right_link == NULL
46 node *temp3 = temp2->right_link;
is a NULL pointer, so you can't
51 temp3->left_link = temp;
which should have been obvious if you used a debugger.

Printing Doubly Linked Lists

I'm currently learning how to work with linked lists, specifically, doubly linked lists, and I have come across a problem with my program when I attempt to print it backwards.
Here is the portion of the code that I need help with:
#include <iostream>
using namespace std;
struct node
{
int data; //int to store data in the list
node *next; //pointer to next value in list
node *prev; //pointer to previous value in list
};
node *appendList(node *current, int newData) //Function to create new nodes in the list
{
node *newNode; //create a new node
newNode = new node;
newNode->data = newData; //Assign data to it
newNode->next = NULL; //At end of list so it points to NULL
newNode->prev = current; //Link new node to the previous value
current->next = newNode; //Link current to the new node
return newNode; //return the new node
}
node *createList(int maxLoop, node *begin, node *current, node *end) //Function to create list
{
//Allocate the starting node
current = new node;
current -> data = 1; //First data value is 1
current -> next = NULL; //next value is NULL
current -> prev = NULL; //previous value is NULL
begin = current; //This is the beginning of the list
for (int count = 2; count <= maxLoop; count++) //Loop to fill the list
{
current = appendList(current, count*count); //Create new nodes and fill with square numbers
}
end = current; //Now we are at the end of the list
return begin; //Return begin, this is the problem; I can't return end as well
}
void printForward (node *p) //Function to print the list forwards
{
node *curr = p; //current is the beginning value of the list
while (curr != NULL) //Continue while current is not at the end of the list
{
cout << curr->data << " "; //Print out the data of current
curr = curr->next; //Move one value along in the list
}
}
void printBackward (node *p) //Function to print the list backwards
{
node *curr = p; //current is the end value of the list
while (curr != NULL) //Continue while current is not at the beginning of the list
{
cout << curr->data << " "; //Print out the data of current
curr = curr->prev; //Move one value back in the list
}
}
int main()
{
//Initialize current, begin, and end
node *current = NULL;
node *begin = NULL;
node *end = NULL;
int maxLoop = 10; //The number of items in the list
cout << "The list has now been created." << endl;
begin = createList(maxLoop, begin, current, end); //function to create the list
cout << "Printed forwards, this list is: ";
printForward(begin); //Function to print the list forwards
cout << endl;
cout << "Printed backwards, this list is: ";
printBackward(end); //Function to print the list backwards
cout << endl;
return 0;
}
The purpose of this program is to create a list, print it forwards, backwards, insert an element, erase an element, and then destroy the list. I have chopped it down to just the create, print forward, and print backward functions.
The issue I have is that in the createList function I am modifying both begin and end but I can only return one or the other. This means that whichever I don't return is still NULL in the main function and therefore does not point to anything. I've tried setting the begin/current/end to not equal NULL but createList won't work if I do that.
Does anyone have any ideas for how I could modify both? Just to be clear, the list HAS TO be created in a function, it would be very easy to just initialize it in the main.
Thanks,
Tristan
Your problem is you're copying the pointers, when you should be passing them by reference, i.e., using a pointer-to-pointer or reference-to-pointer rather than just copying the value the pointer in main is originally pointing to. With what you're doing, you're unable to modify the original pointer variable that was declared in main ... passing-by-reference will allow you to-do that while also keeping all list setup code within your functions.
So for instance, change
node* createList(int maxLoop, node *begin, node *current, node *end)
to
void createList(int maxLoop, node** begin, node** current, node** end)
and then make sure to take the extra dereference into account in the body of your function
Finally, you would call it like:
createList(maxLoop, &begin, &current, &end);
And do the final assign to begin inside the body of the function of createList rather than in main.