链接列表值只指向C中函数内部的更改



我正在尝试在C:中实现一个链表

struct Node{
struct Node *next;
void *data;
};

具有插入功能:

void insert(void *p2Node, void *data)
{
struct Node *newNode;
struct Node **p2p2Node= (struct Node **)p2Node;

if (newNode = malloc(sizeof(struct Node))) /* if successfully allocated */
{
newNode->data = data;

if ((*p2p2Node) != NULL) /* if the list is not empty */
{
newNode->next =  (*p2p2Node)->next;
(*p2p2Node)->next = newNode;
}
else
(*p2p2Node) = newNode;
p2Node = p2p2Node;
}
printf("Inside the insert: %sn", (*p2p2Node)->data);
}

我在main():中调用了insert

int main()
{
char *setA = "liquid ";
char *setB = " lgd";
char *setC = "sample";  
struct Node *nList = malloc(sizeof(struct Node));
insert(nList, setC);
printf("2Get %sn", nList->data);

return 0;
}

未报告任何错误或警告,但该值仅在insert内部更改。回到main(),链接列表仍然为空。

我不明白:main()中的nList是一个空指针。在insert()内部,*p2Node没有更改,我用p2p2Node更改了p2Node指向的值,为什么它不起作用?指针不匹配吗?有没有一种方法可以让它在不修改insert()参数的情况下工作?

谢谢。

使用此代码将值插入到链表中。

struct node{
int data;
struct node* link;
};
struct node *root = NULL;
int len;
int main()
{
append();
display();
addatbegin();
display();
addatafter();
display();
}

将值添加到列表末尾。

void append(){
struct node* temp;
temp = (struct node*)malloc(sizeof(struct node));
printf("Enter the data: ");
scanf("%d", &temp->data);
temp->link = NULL;
if(root == NULL) //list is empty
{
root=temp;
}else
{
struct node* p;
p=root;
while(p->link != NULL)
{
p = p->link;
}
p->link = temp;
}
}

将值添加到列表的开头。

void addatbegin()
{
struct node* temp;
temp = (struct node*)malloc(sizeof(struct node));
printf("Enter the data : ");
scanf("%d", &temp->data);
temp->link = NULL;
if(root == NULL)
{
temp = root;
}
else
{
temp->link = root;
root = temp;
}
}

在节点后添加值

void addatafter()
{
struct node* temp, *p;
int loc, i=1;
printf("Enter the location : ");
scanf("%d", &loc);
if(loc > len)
{
printf("Invalid input.");
}
else
{
p = root;
while(i > loc)
{
p = p->link;
i++;
}
temp = (struct node*)malloc(sizeof(struct node));
printf("Enter the data : ");
scanf("%d", &temp->data);
temp->link = NULL;
temp->link = p->link;
p->link = temp;
}   
}

显示链接列表

void display(){
struct node* temp;
temp = root;
if(temp == NULL)
{
printf("List id empty.n");
}
else
{
while (temp != NULL){
printf("%d -> ", temp->data);
temp = temp->link;
}
printf("nn");
}
}

最新更新