c++ program crashes linked list? - c++

if(tmpPtr->number<tmpPtr->next_number->number)
{
int tmpV1=tmpPtr->next_number->number;
int tmpV2=tmpPtr->number;
tmpPtr->next_number->number=tmpV2;
tmpV2=tmpPtr->number=tmpV1;
}
This is what I have tried so far, this is supposed to be sorting the linked list as member are being added each time. But when the compiler crashes when I try to put in the second node. The break point is the if statement, if(tmpPtr->number<tmpPtr->next_number->number). I tried really hard to figure out what the problem was, but couldnt.

Your problem is that on the second run tmpPtr points to your first element which has a next_number value of NULL. So as soon as you try to dereference it, it will basically reduce itself to a NULL pointer which leads to a SIGSEGV.
after the first run
n->number = input
n->next_number = NULL
h = n
t = n
counter2 = 1
so starting with the second input
n->number
n->next_number = NULL
tmpPtr = h // which is the previous n and therefor h->next_number = NULL
tmpPtr->next_number == NULL // this is your problem since you do not check if next_number is a valid pointer
UPDATE:
if uploaded a (hackish) version of a solution at https://gist.github.com/sahne/c36e835e7c7dbb855076

for the second add, h->next_number is NULL, so on the first iteration of the inner while loop, you dereference NULL (alias of h->next_number->number).
Edit
When you're inserting the 2nd item:
head == tail, so head->next == NULL.
you start the inner loop:
head->number == first inserted item.
head->next == NULL.
head->next->number == dereferenced NULL.

Related

what is wrong with this reverse linklist code?

var reverseList = function(head) {
function reverse(cur,pre){
if(!cur) return pre
next = cur.next
cur.next = pre
return reverse(next,head)
}
return reverse(head.next,head)
}
I tried a recursion way to write this,
this code output is not correct running, whats wrong with this code?
This is what i think:
If we go by your logic for let's say this case (1->2->3->null), then end result is - first node has address of second node in its 'next' & second node has address of first in its 'next'. So, a loop is formed (1->2 and 2->1). If you want to print such a list, it'll end up in an infinite loop kind of situation in an online platform.
As Thomas Mailund has correctly pointed out, null list case also needs to be covered.
I'd also suggest you to keep your variable names distinct from each other to avoid confusion.
(e.g. you used 'next' as variable name in your inner function which is used already for linked list).
Taking these factors into consideration, here's the rectified working version of your code:
var reverseList = function(head) {
var r = null;
function reverse(p, q) {
q.next = r;
r = q;
if (p == null) return q;
return reverse(p.next, p);
}
return (!head) ? head : reverse(head.next,head)
}

Create a checkerboard or "Interweave" two linked-lists. IE changing the pointers of two linked lists

So I have two linked lists, each holding a color:
1.black->2.black->3.black->4.black->5.black->NULL
1.red ->2.red ->3.red ->4.red ->5.red ->NULL
I want the function to return
1.black->2.red ->3.black->4.red ->5.black->NULL
1.red ->2.black->3.red ->4.black->5.red ->NULL.
Lets name the first pointers, firstBlack and firstRed. To achieve this "checkerboard" pattern, I switch the nodes that each first is pointing to with a simple swap to the other list, advance the pointer two spots, then repeat until I'm at the end of the list.
while(firstBlack->next != NULL && firstRed->next != NULL) {
Node * temp = firstBlack->next;
firstBlack->next = firstRed->next;
firstRed->next = temp;
firstBlack = firstBlack->next->next;
firstRed = firstRed->next->next;
}
However, the function isn't doing what it's supposed to although I'm fairly certain that my logic is correct. I am also getting seg faults :(
This is a simple enough code, please use a debugger and debug the code step by step.
Also please post the entire code not just what's in the while loop.
This code should work correctly.
//Some methods to create these linked lists.
pBlackHead = CreateBlackList();
pRedHead = CreateRedList();
firstBlack = pBlackHead;
firstRed = pRedHead;
while(firstBlack->next != NULL && firstRed->next != NULL){
Node * temp = firstBlack->next;
firstBlack->next = firstRed->next;
firstRed->next = temp;
firstBlack = firstBlack->next;
firstRed = firstRed->next;}
While printing the list to check the correctness use pBlackHead , pRedHead. A debugger is not currently available on the system I am using but this should work.
You are advancing two steps without checking end conditions. Because you have an odd number of items, you dereference a null pointer.
You don't need to care which tail originated in which list to swap them
for(; left->next && right->next; left = left->next, right = right->next) {
std::swap(left->next, right->next);
}

How to remove duplicates from linked list which repeats double number of times?

I've been trying to create own linked list class on C++. My task is remove all nodes which data repeats double number of times in list and store only one node if data repeats odd number of times. I've written function removeDuplicates(), but my program crashes when i try to use the function. Implementation here:
void LinkedList::removeDuplicates(){
Node *ptr1, *ptr2, *dup, *toDel;
int counter = 1;
ptr1 = top;
while(ptr1 != NULL && ptr1->next != NULL){
ptr2 = ptr1;
while(ptr2->next != NULL){
if(ptr1->name == ptr2->next->name){
dup = ptr2->next;
ptr2->next = ptr2->next->next;
delete dup;
counter++;
} else {
ptr2 = ptr2->next;
}
}
if(counter % 2 == 0){
toDel = ptr1;
ptr1->next = ptr1->next->next;
ptr1 = ptr1->next;
delete toDel;
}else{
ptr1 = ptr1->next;
}
}
}
Firstly: Please learn to use a debugger. Knowing the exact line where it crashes and looking at the variables and pointers at runtime, and stepping through the code will save you from asking these: "I wrote some code, it's broke, fix it please." 'questions'.
If gdb is unwieldy for you, use visual studio or something.
As Some programmer dude suggested: learn how to debug your code.
Regarding your actual problem:
After your inner loop.
ptr1->next = ptr1->next->next;
is not checked if (ptr1->next == NULL). Thus accessing ptr1->next->next will result in an access violation.
While that check is in the outer while loop condition, the inner while loop may delete and unlink the object from your list.
I'm also fairly certain that you want to reset your counter somewhere in the outer loop, probably right at the start. as it is now, it doesn't count the number of occurences of any one ptr2->name
Also you should initialize variables right in the declaration, it's just good style and may avoid further hassle.
It is also a good idea to set your pointers to NULL after deleting, so you DO get a nice null pointer exception instead of it randomly 'working' or crashing.

Program crashes when opening and processing input files

I'm currently working on a program, and I'm running into a small issue. It's reading data from a text file, and when the numbers are in ascending order, it runs fine, but when I have numbers in a random order, it crashes. I've debugged it and traced it to this if statement, but I can't figure out what the heck I did wrong.
if(tempNode != NULL)
{
struct doublyLinkNode* temp = new doublyLinkNode;
temp->nextNode = tempNode;
temp->previousNode = tempNode->previousNode;
temp->nodeValue = noToInsert;
tempNode->previousNode->nextNode = temp;
tempNode->previousNode= temp;
list->count++;
return true;
} // end if
The list building crashes when a new number to be added precedes the current top of the list. I think the pointer is attempting to write to an invalid pointer.
Your error is to be expected. You want to insert nodes before the current one (tempNode),
and you´re using tempNode->previousNode in the code.
If tempNode happens to be the first node, what´s tempNode->previousNode? Right, NULL
(unless you have a circular list, but then you wouldn´t have this problem). That means
tempNode->previousNode->nextNode = temp; will crash.
As solution to this part, just make an if:
if(tempNode->previousNode != NULL) tempNode->previousNode->nextNode = temp;
(assuming that everything is initialized properly). Depending on how you implemented the list, you may need to change the information what the first node is, too.

Deleting elements from doubly bounded pointer list

I am working on a project where I create a double bounded pointer list, delete several elements, and still be able to read off the list. I have a double bounded pointer list, but am having trouble deleting elements and keeping the list double bounded. This then causes issues when trying to print the list.
Below is the IF statement I've placed in a while loop to help delete unwanted elements. I keep getting a segmentation fault (core dumped).
if ((black2 != black)||(white2 != white)) {
dump = help;
help = help ->next;
dump -> before = temp;
temp -> next = help;
help ->before = temp;
delete dump;
}//if
else { temp = help;
help = help->next;
help ->before = temp; }//else
To maintain properly the doubly linked list you should do something like :
void remove(X *elt) {
X* before = elt->before;
X* after = elt->next;
if (before != NULL) { // assuming first element points to NULL
before->next = after;
}
else {
first = after; // assuming first is a pointer to first element of list
}
if (after != NULL) { // assuming last element points to NULL
after->before = before;
}
else {
last = before; // assuming last is a pointer to last element
}
delete elt;
}
That way, you ensure that elements around current correctly point to each other dealing with special cases of removing first or last element.
But you already have a std::list template in Standard Template Library
One logical issue in your code is the line dump->before = temp.
What this does is that it sets the previous node pointer of dump to temp, as opposed to defining temp as the previous node.
The correct line should read temp = dump->before
PS: Your code is correct assuming that the node you are deleting isn't the first or last node (and you haven't padded with dummy nodes). You should introduce checks for these cases if required.