知道发生什么问题了吗?
想法:
谢谢。
struct Node{
int data;
struct Node *prev;
struct Node *next;
}*HEAD, *TAIL;
int main(){
int temp;
printf(" |-> Insert front : ");
scanf("%d", &temp);
*tempNode = myInsert(temp);
insertFront(tempNode);
}
Node myInsert(int num){
// create new node
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = num;
newNode->prev = NULL;
newNode->next = NULL;
return *newNode;
}
void insertFront(Node *newOne){
if(HEAD==NULL){
printf(" |-> insertFront - HEAD : List empty, adding node - %d.\n", newOne->data);
newOne->prev = newOne;
HEAD = newOne;
}
else{
// insert front
printf(" |-> insertFront - List : Adding node - %d.\n", newOne->data);
newOne->next = HEAD;
HEAD->prev = newOne;
HEAD = newOne;
}
}
[1] 2947分段错误./a.out 失败:139
答案 0 :(得分:0)
您提到的代码很少有问题,首先是这里
Node *newNode = (Node*)malloc(sizeof(Node));
Node
是什么?您需要typedef
struct Node
。对于例如
typedef struct Node{
int data;
struct Node *prev;
struct Node *next;
}Node; /* first typedef it */
Node *HEAD,*TAIL;
第二,这里
insertFront(tempNode);
您正在将tempNode
传递到insertFront()
,并且tempNode
中insertFront()
的更改不会反映在调用函数中,因为它被视为按值调用。您需要传递tempNode
的地址。例如
insertFront(&tempNode);
另外,myInsert()
应该返回newNode
,而不是*newNode
。
尝试此版本:
typedef struct Node{
int data;
struct Node *prev;
struct Node *next;
}Node; /* first typedef it */
Node *HEAD,*TAIL;
Node* myInsert(int); /* declaration */
void insertFront(Node **); /* declaration */
void printNode(Node *); /* declaration */
int main(void){
int temp;
printf(" |-> Insert front : \n");
scanf("%d", &temp);
struct Node *tempNode;
int itr;
printf("enter no of nodes you want to insert onto list \n");
scanf("%d",&itr);
for(int i = 0;i< itr; i++) {
tempNode = myInsert(temp);
insertFront(&tempNode); /* need to pass address else changes in insertFront won't reflect here */
}
printNode(tempNode); /* fun for printing Node info*/
return 0;
}
Node* myInsert(int num){
// create new node
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = num;
newNode->prev = NULL;
newNode->next = NULL;
return newNode;
}
void insertFront(Node **newOne){
if(HEAD==NULL){
printf(" |-> insertFront - HEAD : List empty, adding node - %d.\n", (*newOne)->data);
//newOne->prev = newOne; /* not required as myInsert() already did this */
HEAD = *newOne;
}
else{
// insert front
printf(" |-> insertFront - List : Adding node - %d.\n", (*newOne)->data);
(*newOne)->next = HEAD;
HEAD->prev = (*newOne);
HEAD = (*newOne);
}
}
void printNode(Node *temp) {
while(temp) {
printf("%d\t",temp->data);
temp = temp->next;
}
}