我开始学习链表,但我在升序或降序的正确位置插入时遇到了问题。也许我还没有理解正确。你能帮我理解这里的程序吗?
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;
}
}
你的代码有很多错误。我认为最好添加我的代码版本,而不是指出代码中的错误。这是我的代码。
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;
}
}