有人可以向我解釋為什么此代碼回傳一個隨機負數而不是添加節點嗎?如果洗掉了對 addnode 的呼叫,則 main 函式會正常作業,因此問題出在 addnode 函式上。我不認為是 malloc 有問題,我一生都無法弄清楚是什么。請幫忙,我是 c 的業余愛好者,我對指標的作業原理有一個模糊的理解,所以我猜我的指標有問題。這是完整的代碼:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
int addNode(struct node **head, int value);
void printList(struct node **head);
int main()
{
int value;
struct node *head;
head=NULL;
//int isempty(struct node *head);
for(int i=0;i<10;i )
{
printf("\nInsert node value :");
scanf("%d",&value);
addNode(&head,value);
}
printList(&head);
return 0;
}
int addNode(struct node **head,int value)
{
struct node *newnode;
newnode=(struct node *) malloc(sizeof(struct node));
//if(newnode==NULL)
if(!newnode)
{
printf("Memory allocation error \n");
exit(0);
}
if(*head=NULL)
{
newnode->data=value;
newnode->next=NULL;
*head=newnode;
return 1;
}
else
{
struct node *current;
*current = **head;
while(current != NULL)
{
if(value<=(current->data)){
//περ?πτωση 1ου κ?μβου σε μη κεν? λ?στα
if(current==*head){
newnode->data=value;
newnode->next=*head;
*head=newnode;
return 1;
}
//περ?πτωση ενδι?μεσου κ?μβου
newnode->data=value;
return 1;
}
current = current->next;
}
}
}
/*int isempty(struct node *head){
return (head==NULL);
}*/
void printList(struct node **head) {
struct node *ptr = *head;
printf("\n[ ");
//start from the beginning
while(ptr != NULL) {
printf("(%d) ",ptr->data);
ptr = ptr->next;
}
printf(" ]");
return;
}
uj5u.com熱心網友回復:
好吧,對于初學者來說,您在 addNode 中有一個分配而不是比較
if(*head=NULL) should be if(*head==NULL)
除此之外,我認為您正在嘗試以排序的方式維護元素?但無論如何,您對指標的操作比您需要的要多一些。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/373387.html
