Inserting at the tail of a doubly linked list - c++

I'm working with linked lists for my first time and have to create a function that can insert a node at the end of a doubly linked list. So far I have
void LinkedList::insertAtTail(const value_type& entry) {
Node *newNode = new Node(entry, NULL, tail);
tail->next = newNode;
tail = newNode;
++node_count;
}
The Node class accepts a value to be stored, a value for the next pointer to point to, and a value for the previous pointer in that order. Whenever I try to insert a node here, I get an error saying there was an unhandled exception and there was an access violation in writing to location 0x00000008.
I'm not entirely sure what's going wrong here but I assume it has something to do with dereferencing a null pointer based on the error message. I would really appreciate some help with solving this problem.
EDIT:
I should have clarified early, tail is a pointer that points to the last node in the list. Tail->next accesses the next variable of that last node which, before the function runs, points to NULL but after it executes should point to the new node created.

Where does tail point to initially? If it's NULL then you'll dereference a null pointer when trying to insert the first element.
Does it help if you test tail before dereferencing it?
void LinkedList::insertAtTail(const value_type& entry) {
Node *newNode = new Node(entry, NULL, tail);
if (tail)
tail->next = newNode;
tail = newNode;
++node_count;
}
If tail is null and offsetof(Node, next) is 8 that would explain the access violation, because tail->next would be at the address 0x00000000 + 8 which is 0x00000008, so assigning to tail->next would try to write to memory at that address, which is exactly the error you're seeing.

Assuming your LinkedList has both a head AND tail, maybe try:
void LinkedList::insertAtTail(const value_type& entry)
{
Node *newNode = new Node(entry, NULL, tail);
if (tail)
tail->next = newNode;
tail = newNode;
if (!head)
head = newNode;
++node_count;
}
Just a shot in the dark

It's difficult to tell what's causing the error without knowing the state of the list before the insertion operation (which is actually append rather than insert, by the way).
There's a good chance you're not handling the initial case of appending to an empty list. The basic algorithm is (an empty list is indicated by a NULL head pointer, everything else is indeterminate):
def append (entry):
# Common stuff no matter the current list state.
node = new Node()
node->payload = entry
node->next = NULL
# Make first entry in empty list.
if head = NULL:
node->prev = NULL
head = node
tail = node
return
# Otherwise, we are appending to existing list.
next->prev = tail
tail->next = node
tail = node

Related

how can I reverse my Linked list . I wrote following code but this is giving only first node's data as output

Node *reverse(Node *head)
{
Node *answer = NULL, *p = head, *address = NULL;
while (p != NULL)
{
address = p;
address->next = answer;
answer = address;
p = p->next;
}
return answer;
}
In order to reverse a singly linked list, you need to keep one node in memory to be able to relink backwards.
It could look like this:
Node* reverse(Node* head) {
if(head) { // must have at least one node
Node* curr = head->next; // head + 1
head->next = nullptr; // this will be the new last node
Node* next; // for saving next while relinking
while(curr) { // while curr != nullptr
next = curr->next; // save the next pointer
curr->next = head; // relink backwards
head = curr; // move head forward
curr = next; // move curr forward
}
// head now points at the new start of the list automatically
}
return head;
}
Demo
I wrote following code but this is giving only first node's data as output
Because, in reverse() function, you are breaking the link of first node from rest of the list and returning it.
Look at this part of code:
address = p;
address->next = answer;
answer = address;
p = p->next;
In first iteration of while loop this is what happening:
Pointer address will point to head of list (as p is initialised with head) and, in the next statement, you are doing address->next = answer (note that answer is initialised with NULL). So, address->next is assigned NULL. Both, pointer p and pointer address are still pointing same node. After this, you are doing p = p->next, this will assign NULL to p because p->next is NULL. As, p is NULL, the while loop condition results in false and loop exits and function end up returning the first node.
You should assign p to its next before assigning answer to address->next, like this:
while (p != NULL)
{
address = p;
p = p->next; // moved up
address->next = answer;
answer = address;
}
Suggestion:
In C++, you should use nullptr instead of NULL.
Reversing a linked list, in essence, is pretty much flipping the arrows:
Original: A->B->C->D->null
Intermediate: null<-A<-B<-C<-D
Reversed: D->C->B->A->null
void reverseList(void)
{
Node *prev = nullptr;
Node *curr = head;
while (curr)
{
Node *nxt = curr->next;
curr->next = prev;
prev = curr;
curr = nxt;
}
head = prev;
}
The crux of the solution will be to use the previous and current node strategy to loop through the list. On lines two and line 3, I set the prev to null and curr to the head respectively. Next, I set the while loop, which will run until curr is equal to null or has reached the end of the list. In the 3rd and 4th lines of the body of the while loop, I set prev to curr and curr to nxt to help me move through the list and keep the traversal going while keeping track of the previous and current nodes.
I am storing the next of the current node in a temporary node nxt since it gets modified later.
Now, curr->next = prev is the statement that does some work. Flipping of the arrows takes place through this statement. Instead of pointing to the next node, we point the next of the current node to the previous node.
Now, we need to take care of the head node only. On the last line, head=prev, prev is the last node in the list. We set the head equal to that prev node in the list, which completes our code to reverse a list.
Suppose you have any trouble visualizing the algorithm. In that case, you even have the privilege to print the data stored in the current and previous nodes after each line in the while loop for a better understanding.
Hope this helps getting the gist of how we reverse a linked list.

Exception Handled this was Nullptr?

I've been working on this assignment, and been running into this bug I haven't been able to fix for hours. It's saying unhandled exception thrown, read access violation. I heard you're not suppose to deference nullptrs, however I don't believe that's what I'm doing.
void Linkedlist::insertnode(string key, string value) {
Node* newNode; //This points to the following node
Node* cursor; //This will traverse through list
newNode = new Node; //create a new node
newNode->data = new HashEntry(key, value); //Initialize the data
newNode->next = nullptr; //Leave the pointer for the node following after empty at inception;
if (!head) {
head = newNode; //if head is empty, this will make the first user input the head
return;
}
else {
cursor = head;
while (cursor->next)
;
//We'll traverse list to add newNode to tail
cursor->next = newNode; //for now the order doesn't matter since they're strings so we add new cluster to tail
}
}
"read access violation" is most likely an uninitialized variable. It happens when you try to access data from memory outside your program memory. This is a protection mechanism of your system to prevent you from overwriting data you shouldn't.
Therefore I'd recommend checking your definition of the class HashEntry as well as the definition of the Pointer head which isn't in your posted code.
What also came in my view is your infinite loop while (cursor->next);
I get what you're trying to do - iterate over the elements until you're at the end of the list. But you have to use an iterator:
Node* iterator = cursor;
while (iterator)
{
iterator = iterator->next;
}

How to delete an object ( node ) which is in use

I have the following code that inserts item to a double-linked list using iterator. This is how we are asked to do it. The code works, but the problem is that I have absolute memory leak of 24 bytes.
NodeIterator<T> insert(NodeIterator<T> & itrPassed, const T datapassed)
{
Node<T> * newNode = new Node<T>(datapassed);
Node<T>* previousOfCurrent = itrPassed.getCurrent()->previous;
previousOfCurrent-> next = newNode;
newNode -> previous = previousOfCurrent;
newNode -> next = itrPassed.getCurrent();
itrPassed.setCurrent(newNode);
return itrPassed;
}
I know that the problem is caused by this line Node<T> * newNode = new Node<T>(datapassed);. I can't delete the newNode object as I am returning an iterator pointing to it and it is used in my linked list.
How to solve this problem ?
One problem I see is that you are not updating the previous of the current node. The previous of the current node still points to the old node. As a consequence, if you are iterating over the nodes using previous, you are going to skip over the newly created node.
The other problem I see is that you are accessing previousOfCurrent without checking whether it is a valid pointer.
Not sure whether fixing them will fix your memory leak problem.
NodeIterator<T> insert(NodeIterator<T> & itrPassed, const T datapassed)
{
Node<T> * newNode = new Node<T>(datapassed);
Node<T>* previousOfCurrent = itrPassed.getCurrent()->previous;
// Prevent accessing a nullptr
if ( previousOfCurrent != nullptr )
{
previousOfCurrent-> next = newNode;
newNode -> previous = previousOfCurrent;
}
newNode -> next = itrPassed.getCurrent();
// Add this
itrPassed.getCurrent()->previous = newNode;
itrPassed.setCurrent(newNode);
return itrPassed;
}

What faulty logic is causing this push_back(...) function of my linked list to fail?

For some reason
template <typename T> void SinglyLinkedList<T>::push_back ( T v )
{
node * newNode = new node;
newNode->val = v;
newNode->next = NULL;
if (_root != NULL)
{
node * thisNode = _root;
while (thisNode->next != NULL) thisNode = thisNode->next;
thisNode->next = newNode;
}
else
{
_root = newNode;
}
}
has incorrect logic and I need some help figuring out what it is. When I tested
int myArray [] = { 1, 69, -23942, 69, 56, 67 };
SinglyLinkedList<int> myList(myArray, sizeof(myArray)/sizeof(int));
myList.push_back(33);
myList.print();
it printed
1->69->-23942->69->56->33->33->33->33->33-> ...
until the program crashed.
I'll explain my logic so that you can pinpoint where I'm wrong:
node * newNode = new node;
newNode->val = v;
newNode->next = NULL;
creates a new node object on the heap and initializes its value to v and its pointer to the next node as NULL. This is the node that will be added on to the end of the list. The end of the list will either be
(1) a final element whose next is NULL
or
(2) non-existent, meaning there are no elements, hence no final element
For micro-optimability, because I expect case (1) to occur more often I put it inside the if clause that is to follow and put case (2) inside the else clause.
Case (2) occurs if and only if the _root node is NULL, meaning the list is empty, and the handling of it is simply to make that _root be newNode:
else
{
_root = newNode;
}
Case (1) requires finding the final node and setting its next to newNode, which should be accomplished very simply with the 3 lines
node * thisNode = _root;
while (thisNode->next != NULL) thisNode = thisNode->next;
thisNode->next = newNode;
What is the flaw in that logic?
The error is in your constructor. This line:
delete lastNode;
is deleting memory that your are still using (the node that lastnode points to has just been put in your list).
Remove that line.
Edit: further explanation. Once the memory that lastnode points to is freed, the runtime can then use that memory again for another call to new. In your your case you have probably ended up with newNode and thisNode pointing to the same location, causing the node to point to itself.
when you delete last node, the node which its next is null deleted and the previous one next pointer is not null so when you parse the linked list you directed to unknown memory places!!!

Remove all nodes in linked list

I have a linked list contains 3 nodes like the image shown:
There is a head pointer and temp1 pointer point to the front of the list, and tail point points at the end of the list.
I want to remove all the nodes, and change it back to its original initial form ( tail = NULL, head = first_node , but the first node doesn't have any value in the data and next field).
Because I want to start putting up some new values in it. To remove all those data, is this code going to remove nodes inside this linked list and left with the first node with no values in data and next field?
This code is in C++:
while(temp1!=tail)
{
temp1 = temp1->next;
if(temp1->next == tail)
{
tail=temp1;
temp1 = temp1->next;
free(temp1);
}
}
But then, does this mean only the last node will be deleted? are there any way to delete all the nodes except the first one?
To delete all nodes except the first node, you can try below code.
temp1 = head->next;
while(temp1!=NULL) // as I am considering tail->next = NULL
{
head->next = temp1->next;
temp1->next = NULL;
free(temp1);
temp1 = head->next;
}
This will delete all nodes except first one. But the data with the first node will remain as it is.
Disclaimer: I assume it's only for learning purposes and in real-world scenario you would use std::list<> or similar container.
For single-linked list, you can just drop all this burden an let the stdlib manage the pointers:
class Node {
std::unique_ptr<Node> next;
};
You can safely use .reset() method to make operations on the list:
Given current_ptr, the pointer that was managed by *this, performs the following actions, in this order:
Saves a copy of the current pointer old_ptr = current_ptr
Overwrites the current pointer with the argument current_ptr = ptr
If the old pointer was non-empty, deletes the previously managed object if(old_ptr != nullptr) get_deleter()(old_ptr).
From http://en.cppreference.com/w/cpp/memory/unique_ptr/reset.
And that's pretty much what you would do when deleting. I believe you can also use unique_ptr::swap(), to easily manipulate your nodes.
Instead of free, C++ uses delete function.
Check the link to have deep knowledge about all kind of operations(including recursive or iterative delete) on linked lists.
temp1 = head->next;
while(temp1!=NULL) // as I am considering tail->next = NULL
{
head->next = temp1->next;
temp1->next = NULL;
free(temp1);
temp1 = head->next;
}
The logic for this would be more correct if it is this way.
After the statement
free(temp1);
Add the condition
if (head -> next != NULL)
temp1 = head->next;
Since after deleting the last node there is no point in reassigning the address of head pointer to temp1.