我正在尝试按升序排序链表, 但由于某种原因,代码给了我一个值 如果有人可以告诉我为什么我会感恩 看到这个功能:
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;
}
}
答案 0 :(得分:3)
最后插入是错误的:
if (q == 0 ) // if it is the last value
q = t;
您只需修改q
,但永远不会更新最后一个元素的链接。你应该试试:
if (q==0) // past end of list
prev->next = t; // next of last element is t
---------- EDIT -------------
通过循环管理指针是错误的,以下工作并且应该非常清楚(只有一个指针用于在列表中移动):
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;
}