我开始学习链接列表,我遇到了按升序或降序插入正确位置的问题。也许我没有理解它。你能帮我理解这里的程序。
void insert(int x) {
Node* temp = (Node*) malloc(sizeof(Node));
Node* prev = NULL;
Node* curr = head;
if(head!= NULL){
prev = curr;
while(prev != NULL){
prev = prev->next;
}
if(prev->data > x){
temp->data = x;
temp->next=head;
head=temp;
}else{
temp->data = x;
temp->next = NULL;
prev->next = temp;
}
}else{
head = temp;
}
}
答案 0 :(得分:0)
您的代码有很多错误。我认为最好添加我的代码版本而不是指出代码中的错误。这是我的代码。
void insert(int x)
{
Node* temp = (Node*) malloc(sizeof(Node));
temp->data = x;
temp->next = NULL;
Node* curr=head;
if(curr==NULL)//if this were the first element...
{
head = temp;
return;
}
if(curr->data > x)
//special case:
//adding element at the head itself.
//you need to change the head pointer then.
{
temp->next = curr;
head = temp;
return;
}
while(curr->next!=NULL)
{
if(curr->next->data > x)
{
temp->next = curr->next;
curr->next =temp;
return;
}
curr = curr->next;
}
if(curr->next==NULL)
//adding the element at the end...
{
curr->next = temp;
return;
}
}