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
1 Answer 1
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
Jean-Baptiste Yunès
see my new (tested) solution
lang-cpp
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.