Same code giving different results in Online IDE and local IDE - c++

Below program is used to remove the duplicates from a sorted singly linked list. The code gives garbage values in online IDE. But when I comment the line .
delete curr;
The program works fine in online IDE itself. Here is the function I wrote. The other parts of the code are well-defined(not by me) by the online Judge.
And also the code without commenting the line delete curr; works fine in local IDE(codeblocks).
FULL PROGRAM:http://ideone.com/9bHab0
Why do I get the garbage values?
Node *removeDuplicates(Node *root)
{
// your code goes here
struct Node* curr = root,*prev = NULL;
while(curr)
{
if(prev==NULL)
prev = curr;
else if(curr->data!=prev->data)
prev = curr;
else
{
prev->next = curr->next;
delete curr;
curr = prev->next;
}
}
return root;
}
EDIT: One could see the pointer whose location is deleted, is reassigned immediately. Thus there couldn't be a dangling pointer here!

Lets take a very simple example, with a two-node list, where you have e.g.
node1 -> node2
With the first iteration then prev is NULL so you do prev = curr. Now curr and prev points to the same node.
That means in the second iteration both if conditions are false (prev != NULL and curr->data == prev->data) you go into the else part, where you have
prev->next = curr->next;
delete curr;
curr = prev->next;
Here you delete curr but curr is pointing to the same memory as prev, leading to undefined behavior in the assignment curr = prev->next, as you now dereference the stray pointer prev.
To make matters worse, you then enter a third iteration where prev is still pointing to the deleted first node, and again dereference the invalid prev pointer (in your second if condition) and you once again end up in the else part where you continue the invalid dereferencing. And so on in infinity (or you get a crash).

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.

How do I create a function to change the value of the last node to 1000?

I tried to create a code for it. However, it didn't work. Here's my previous attempted code:
void modifyLastNode(node*) {
curr = head;
while (Curr != NULL && curr->data != 99) {
temp = new node;
temp->data = 1000;
temp->next = curr;
}
}
Aside from the syntax errors that prevent your code from even compiling properly (ie, curr, head, Curr, and temp are undefined), the code also contains several logic errors:
You are ignoring the input parameter.
You are not changing what curr points to while looping, so you end up checking the data field of the same node over and over, so you end up in an endless loop.
You are allocating (and leaking) a new node on each loop iteration. Searching should not be creating new nodes at all.
Checking the data field is the wrong way to detect the last node in the list. The last node has its next field set to NULL, that is what you should be looking for. Imagine calling modifyLastNode() twice on the same list. The 1st call would look for 99 (which in your example is the last node in the list, but in a production system it may not be), changes it to 1000, and then the 2nd call cannot find 99 anymore.
You need something more like this instead:
void modifyLastNode(node *head) {
if (head) {
node *curr = head;
while (curr->next != NULL) {
curr = curr->next;
}
curr->data = 1000;
}
}

Can't Delete My Temporary Pointers?

I'm having an issue with deleting pointers. I don't think I'm doing anything compiler illegal or anything, but perhaps I am, so I would appreciate it if someone could explain the flaw in my logic. I'm hoping the below function should be enough to help, as the whole thing would be a lot to transcribe, but if any more of the code is required, please let me know and I'll add it!
The below is a function to remove lockers from a linked list I've created. I've done my best to cover every conceivable case. The problem arises when I try to actually deallocate the memory of a locker I want to delete. The lines where I've tried to delete the temp variable that references that locked are commented out, because the code breaks with them included. Obviously, though, without them, I can't delete the lockers like I want.
int SelfStorageList::removeLockersOverdue() {
int lockersDeleted = 0;
if (isEmpty()) {
return 0;
}
if (head->objLocker.isRentOverdue && head==tail) { //If that was the only locker, the tail needs to be updated to = head = 0
delete head;
head = tail = 0;
return ++lockersDeleted;
}
LockerNode *prev = head;
LockerNode *curr = head->next;
while (curr != 0) {
if((curr == tail) && curr->objLocker.isRentOverdue) { //If the current locker is tail and needs deleting
LockerNode *temp = curr;
curr = prev;
//delete temp;
lockersDeleted++;
}
if(prev->objLocker.isRentOverdue) { //General case: Previous locker needs deleting
LockerNode *temp = prev;
prev = prev->next;
curr = curr->next;
//delete temp;
lockersDeleted++;
}
else { //Update the pointers if not updated anywhere else
prev = prev->next;
curr = curr->next;
}
}
return lockersDeleted;
}
Any "pointers"? (Terrible pun. :p )
Because you're maintaining a singly-linked list, I see you're keeping track of a prev pointer as you're iterating through your list. That's as it should be, of course, since you can't get the previous node of a given node in a linked list if it's singly-linked without remembering what its previous node was. Your problem is simply that your logic is busted: If a deletion is needed, you need to be deleting the curr node, and patching up the prev node to point its next pointer to curr->next before you delete curr.
Think about it: What you're doing is deleting the prev node, but there's likely a "more previous than that" node that's still pointing to the prev node that you just deleted. The next time you iterate through the list, you'll be iterating into formerly allocated nodes, which may be allocated for some entirely different purpose by that point. Your memory allocator is failing some internal assertion because likely on the next time you call removeLockersOverdue(), the memory has NOT yet been allocated to something else, and you're still finding the same node there that you already deleted, and finding again that it's overdue, and deleting it again, and your memory allocator is complaining that you're deleting memory that isn't allocated. (It would be really nice if it gave you that clear of a message, wouldn't it!)
Also, your special case stuff for handling the very first node & last node can be simplified & commonized; I'll avoid rewriting it for you so you can see if you can simplify it yourself.
while (curr != 0) {
if((curr == tail) && curr->objLocker.isRentOverdue) {
LockerNode *temp = curr;
curr = prev;
//delete temp;
lockersDeleted++;
}
You are not updating the previous node's next pointer here, so it ends up dangling (pointing to memory that is deleted). You also leave tail pointing at the deleted node.
if(prev->objLocker.isRentOverdue) {
LockerNode *temp = prev;
prev = prev->next;
curr = curr->next;
//delete temp;
lockersDeleted++;
}
Again, you don't update the next pointer in the list that points at the deleted node.
else { //Update the pointers if not updated anywhere else
prev = prev->next;
curr = curr->next;
}
}
I think you are greatly confusing yourself by carrying around two pointers in the loop. Try to write it again with just a single pointer tracking the node you are currently examining, and draw some pictures of the three possible cases (remove first node, remove last node, remove internal node) to ensure you are getting the removal logic right.

Inserting at the tail of a doubly linked list

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

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.