inserting integer into linked list in ascending order [closed] - c++

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 9 years ago.
Improve this question
I'm trying to insert a new element into a linked list in ascending order, my code for inputting 3,1,9,7,5 outputs 1,1,1,1,1,1 however the output I want is 1,3,5,7,9
head is actually in a private instance variable for the class List and this is a member function
It is called as:
List a;
a.insertInOrder(3); a.insertInOrder(1); a.insertInOrder(9); a.insertInOrder(7); insertInOrder(5);
the output is 1,1,1,1,1
void List::insertInOrder( int data) {
Node *newNode = new Node;
newNode->data=data;
if(head == null || head->data > data) {
newNode->next = head;
head = newNode;
}
else{
Node *cur = head;
while(cur->next != null && current->next->data < data)
cur = cur->next;
newNode->next = cur->next;
cur->next = newNode;
}
}

Seems mostly valid, but:
while(cur->next != null && current->next->data < data)
Here you refer to "cur" in one clause, and "current" in the other clause.
"current' does no appear to exist, but perhaps you have globals?
But, even that would just screw up the ordering, so I suspect the error is in your output code, rather than your sort code.

You aren't incrementing nextC, so your while loop is comparing data to just one number. cur does nothing since you aren't using it in the conditional like you are with nextC.
while(cur->next != null && nextC->data < data) //nextC->data is set only once
cur = cur->next; //cur incremented, but for what?

Related

This assignment is designed to explore linked lists so you will implement a singly linked-list to hold a collection of bids loaded from a CSV file [closed]

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 9 months ago.
Improve this question
I need help please It keeps giving me the same number and not a different one.
Bid LinkedList::Search(string bidId) {
// FIXME (6): Implement search logic
// special case if matching node is the head
// make head point to the next node in the list
//decrease size count
//return
// start at the head of the list
// keep searching until end reached with while loop (next != nullptr
// if the current node matches, return it
// else current node is equal to next node
//return bid
Node* temp = head;
Node* holder = new Node;
holder->bid.bidId = "";
while (temp != nullptr) {
cout << temp->bid.bidId << endl;
if (temp->bid.bidId == bidId) {
return temp->bid;
}
temp = temp->next;
return holder->bid;
}
}
Just remove everything with a holder. And at the end throw an exception when nothing was found. Alternatively return std::optional<Bid>.

I have created function to modify a node in Linkedlist in C++ but its not working: [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
This Function is Created in LinkedList to modify a node at a given position. But, this function is not working properly and it is giving some random values.
void update_data(int old, int new_data) {//Function toupdate node
Node *curr=header;//Data members
int pos = 0;
while(curr->next!=NULL) {
if(curr->isbn == old)
{
curr->isbn = new_data;
cout<<old<<" Found at position "<<pos<<" Replaced with "<<new_data<<endl;;
}
curr = curr->next;
pos++;
}
}
For starters the variable pos is not used within the function.
Secondly the condition of the while loop
while(curr->next!=NULL) {
is incorrect and in general can invoke undefined behavior because the pointer header can be equal to nullptr. And moreover if the list contains only one node pointed to by the pointer header and its data member isbn is equal to the value of the variable old it will not be changed.
The function should not output any message.
The function can look the following way
void update_data( int old, int new_data )
{//Function toupdate node
for ( Node *curr = header; curr != nullptr; curr = curr->next )
{
if ( curr->isbn == old )
{
curr->isbn = new_data;
}
}
}

Showing Segmentation Fault when Attempting to Reverse a Linked List [closed]

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 3 years ago.
Improve this question
I tried reversing a section of a singly Linked list using this code.
Here startOfSec is the pointer at the starting node of the section of the linked list which is to be reversed, and endofSec is the pointer to the last node of that section.
Now, with this code, I'm getting segmentation fault but if I replace endOfSec->next with NULL (I'm changing the value of the pointer, pointing to the last node of the section(which is to be reversed) of the original linked list, to NULL as well) in the while loop condition, it works perfectly!
void reverseList(ListNode* startOfSec, ListNode *endOfSec){
ListNode *prev = NULL;
ListNode *curr = startOfSec;
ListNode *nxt;
while(curr!=endOfSec->next){
nxt = curr->next;
curr->next = prev;
prev = curr;
curr = nxt;
}
}
Callsite:
//code to get start and end pointers
reverseList(start, end);
I expected my code to reverse the section of the list without the need of setting end->next pointer as NULL.
There are a couple of problems with this code, some easier to fix than others. For this specific segmentation fault, a code walkthrough reveals the cause. Let's look at what happens with a simple example. (You should learn how to do this on your own, either by hand or using a debugger.)
start -> end -> NULL
This is a list with two elements, one named "start" and the other "end". Meh, let's say "start" and "end" are also pointers to the nodes. It's a little ambiguous, but it should not cause problems this time. Now reverse the list.
reverseList(start, end);
Before the first iteration of the loop in reverseList (i.e. after the initializations), your data looks like the following.
startOfSec == start
endOfSec == end; endOfSec->next == NULL;
prev == NULL
curr == start
nxt == /* uninitialized */
start -> end -> NULL
After the first iteration, the data has been updated.
startOfSec == start
endOfSec == end; endOfSec->next == NULL;
prev == start
curr == end
nxt == end
start -> NULL
end -> NULL
After the second iteration, the data has been updated.
startOfSec == start
endOfSec == end; endOfSec->next == start;
prev == end
curr == NULL
nxt == NULL
end -> start -> NULL
Congrats, the list has been reversed. Now all we have to do is exit the loop, so we would like curr to equal endOfSec->next. However, NULL is not equal to start, so we continue into a third iteration, and crash when we try to read curr->next (a.k.a. NULL->next).
Overall, you need to revise how you track the beginning and end of the section to reverse. The current crash comes about because you lose track of the end of the section. (Maybe check prev != endOfSec instead?) You will also have a problem if the end of the section is not the end of the list (the part of the list after the reversed section will be lost in limbo), but that is easy to fix by changing how prev is initialized. The biggest problem I see is when the beginning of the section is not the beginning of the list – changing a singly-linked list requires modifications to the node before the change (a.k.a. the node before startOfSec).

Search function - Linked List [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am working on a search function to search a linked list for a specific value. When it finds that value I want to output its position. I cannot seem to get past the first node without getting an error. I think something is wrong with the loops but I'm not sure what.
int NumberList::search(double num)
{
ListNode *nodePtr;
nodePtr=head;
int i=0;
while (nodePtr->value!= NULL)
{
i=i+1;
if (nodePtr->value==num)
return i;
else
nodePtr=nodePtr->next;
}
return 0;
}
Your while loop is incorect. You should be testing that nodePtr is not NULL
while (nodePtr != NULL)
{
i = i + 1;
if (nodePtr->value == num)
return i;
else
nodePtr = nodePtr->next;
}
Also this is a perfect reason to use nullptr instead of NULL when dealing with pointers. If you had use nullptr then
while (nodePtr->value!= nullptr)
Would give you a compiler error as you cannot compare a double to nullptr
I do not know how the corresponding class is defined but I think in any case the function should look the following way
int NumberList::search(double num)
{
ListNode *nodePtr = head;
int i = 0;
while ( nodePtr != NULL && nodePtr->value != num )
{
++i;
nodePtr = nodePtr->next
}
return nodePtr != NULL ? ++i : 0;
}
It is difficult to compare exactly two floating numbers. You should use a method of comparison that for example takes into account an epsilon.
Take also into account that other functions as for example the function that adds nodes to the list can also be wrong.:)
Your while loop condition should be:
while (nodePtr != NULL)
Because of this error you are likely visiting a node who's pointer is NULL And by dereferencing this you are causing undefined behavior.
You don't show the ListNode type but I'm guessing the value is a double.
while (nodePtr->value != NULL)
Here you're checking if the double is not NULL (NULL is essentially 0). But you need to test nodePtr against NULL.
Note: Consider using nullptr instead of NULL, nullptr is the type safe value for a null pointer and would have produced a compilation error.
error: invalid operands of types 'double' and 'std::nullptr_t' to binary 'operator=='

Remove node at the TAIL Linked List C++ [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
All, I'm creating a function that would remove the tail from a linked list. And My function works fine for just one iteration but it doesn't for subsequent ones.
Could anybody shed some light?
Thanks
int List::removeAtTail(){
if(head == NULL)
{
cout << "Node cannot be deleted from an empty linkedList" << endl;
}
if(curr->next= NULL)
{
curr->next=curr;
}
return 0;
}
And also, if I would like to return the element that I deleted, how would I go around at doing that?
There are many ways this can be done, following is one:
int List::removeAtTail(){
while(curr != NULL) {
if(curr->next == NULL) { // depending on your implementation you might use Tail
int temp = *curr;
delete curr;
return temp;
}
curr = curr->next;
}
return 0;
}
Notice how we iterate through the list until we find the last item. At that point we store it in a temporary variable before freeing the memory. Lastly we return the value stored in the temporary variable.