1

I'm trying to make sorted linked list in ascending order , but for some reason the code give me one value if some one can tell me why I will be thankful see this function:

void AddNode(Node *&head){
 int temp;
 Node *q;
 Node *prev = 0; 
 Node *t;
 cout <<"enter a number : ";
 cin >> temp;
 t = new Node ;
 t->number = temp;
 t->next = 0;
 if (head == 0) {
 head = t;
 } else {
 q = head;
 while (q != 0 ){
 prev = q;
 if(q->number > t->number){
 prev->next = t;
 t->next = q;
 break; 
 }
 q = q->next; // counter 
 }
 if (q == 0 ) // if it is the last value
 q = t;
 }
 }
xhallix
3,0115 gold badges40 silver badges57 bronze badges
asked Apr 21, 2016 at 14:26
3
  • That parameter?? It smells. Anyway If it compiles then you need to step-over your code to see what is exactly happening. Using F-10 on Visual Studio Commented Apr 21, 2016 at 14:28
  • You don't update head when the new node is inserted in front. Also, q = t at the end doesn't do anything useful - you are updating a local variable but aren't using this new value. Commented Apr 21, 2016 at 14:30
  • @FirstStep: What should the OP do if using Eclipse or Code::Blocks? Maybe the OP should use a debugger? There are other IDEs besides Visual Studio. Commented Apr 21, 2016 at 14:51

1 Answer 1

3

Inserting at the end is wrong:

if (q == 0 ) // if it is the last value
 q = t; 

You just modify q but never update the link of the last element. You should try:

if (q==0) // past end of list
 prev->next = t; // next of last element is t

----------EDIT-------------

Your management of pointers through looping is wrong, the following works and should be much clear (only one pointer is used to move in the list):

if (head == 0) { // empty list
 head = t;
} else if (t->number < head->number) { // insert in first place
 t->next = head;
 head = t;
} else { // general case
 q = head;
 while (q->next != 0 && q->next->number<t->number) {
 q = q->next;
 }
 cout << "insert after " << q->number << endl;
 t->next = q->next;
 q->next = t;
}
answered Apr 21, 2016 at 14:32

1 Comment

see my new (tested) solution

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.