我已经实现了一个短链接列表代码,以添加到列表的开头.
然而,头总是包含NULL.我真的不明白为什么它以这种方式行事.任何帮助表示赞赏!以下是代码:
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int iData;
struct node *next;
} Node;
void add2Beg(Node* head, int num);
int main(int argc, char const *argv[])
{
Node *head = NULL;
add2Beg(head, 5);
if (head == NULL)
printf("nothing in head !!!\n");
else{
printf("not null\n");
}
add2Beg(head, 15);
return 0;
}
//adds to the beginning of the linked list
void add2Beg(Node* head, int num)
{
//create a temporary location to hold the new entry
Node* temp = (Node *)malloc(sizeof(Node));
temp->iData = num;
if(head == NULL)
{
head = temp;
printf("inside add2Beg\n");
printf("%d\n", head->iData);
head->next = NULL;
printf("exiting add2Beg\n");
}
else
{
temp->next = head;
printf("%p\n", temp->next);
head = temp;
}
}
Run Code Online (Sandbox Code Playgroud)
因为head里面的变量add2Beg()是该函数的本地变量.为它指定一个新的指针值(head = temp;)只会更改函数内的head变量.你需要传入一个指向指针的指针:
void add2Beg(Node** head, int num)
Run Code Online (Sandbox Code Playgroud)
然后*head在函数内部使用:
if(*head == NULL)
{
*head = temp;
Run Code Online (Sandbox Code Playgroud)
小心像head->next = NULL;这样的行- 这应该被重写为(*head)->next = NULL;或(**head).next = NULL;.
等等.然后像这样调用函数:
add2Beg(&head, 15);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1550 次 |
| 最近记录: |