2

I'm getting mad with infinite loop, what do you think is suitable solution?

void sorting () {
  node * temphead = head;
  node * tempnode = NULL;

  for (int i=0; i<count; i++) {
    for (int j=0; j<count-i; j++) {
      if (temphead->data > temphead->next->data) {
        tempnode = temphead;
        temphead = temphead->next;
        temphead->next = tempnode;
      }

      temphead=temphead->next;
      count++;
    }
  }
}

I tried to increment count and use many conditions with while- before and after the for loop with no result

2 Answers 2

5

An easier way to slide through a linked list is like this:

for (node *current = head; current != nullptr; current = current->next) {
    // This will run through all of the nodes until we reach the end.
}

And to slide to the second to last item (ensuring that node->next exists) looks like this:

for (node *current = head; current->next != nullptr; current = current->next) {
    // Go through all of the nodes that have a 'next' node.
}

If you want to count how many items are in a linked list, you do something like this:

int count = 0;
for (node *current = head; current != nullptr; current = current->next) {
    count = count + 1;
}

So a selection type sort like you have above would look like this:

for (node *index = head; index->next != nullptr; index = index->next) {
  for (node *selection = index->next; selection != nullptr; selection = selection->next) {
    if (index->data > selection->data) {
      swap(index->data, selection->data);
    }
  }
}

Although sorting linked lists is generally not the best way to go (unless you're performing a merge).

Sign up to request clarification or add additional context in comments.

4 Comments

I got it and that's what I really need, but when I print that on screen still non-sorted :(. Thank you for advice.
Hmm.. I did that from memory, I'll debug it and repost a working version shortly.
Fixed. Rather than swapping the nodes themselves, I just swapped the data.
Oh! how I did not notice! I appreciate your help :)
2

the problem is you are looping till count and you are incrementing count in every run of the loop//remove line count++ to avoid remove infinite loop

2 Comments

Looks like he wants to loop over list (by count) and count elements in the same loop :)
should have duplicate count variables like count1 then(or better rename as size and count),if you are trying to do like what @Slava says

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.