0
我想插入一个元素排序的循环双向链表,,这里是我的尝试:插入元件插入排序的循环双向链表
void insertSorted(Node *&head,int x){
Node *temp = new Node();
temp->data = x;
temp->next = temp;
temp->prev = temp;
if(head == NULL){
head = temp;
return;
}
Node *p = head;
Node *q = NULL;
do{
q = p;
p=p->next;
}while(p != head && x>p->data);
if(q == NULL){
temp->next = head;
head->prev = temp;
head = temp;
}
else {
q->next = temp;
if(p!=NULL){
temp->next = p;
p->prev = temp;
}
temp->prev = q;
}
}
代码工作,但问题是与第一元素每次它没有排序,,,例子插入10 9 8 1 2 ,,,输出将是10 1 2 8 9 ,,它应该是1 2 8 9 10
听起来像你应该做一些调试。 –
该列表是正确的。它是循环的,所以10开始或结束,取决于你开始打印的位置。所以我会说'head'不是指向你想要的节点。调试器将帮助您了解这一点。 – user3386109
你忘了更新'head'。够了吗?还是需要进一步的帮助? – Beta