gpt4 book ai didi

c - C 参数值中的单链表

转载 作者:行者123 更新时间:2023-11-30 16:58:40 25 4
gpt4 key购买 nike

我在这方面有点新手。只是想问为什么 start 的值没有改变,但是 p 的值在每次连续调用期间如何改变?

代码如下:

#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
int elt;
struct Node *next;
} node;

void insert (int, node *);
void delete (int, node *);
void print (node *);
int find (int, node *);
void insertp (int, node *);
node *findp (int, node *);

main ()
{
node *start, *temp;
node *q;
start = (node *) malloc (sizeof (node));
temp = start;
temp->next = NULL;
printf ("Start before while : %d \n", start);
printf ("Start is pointing to : %d \n", start->next);
int choice;
while (1) {
printf
("1.Insert \n2.Display \n3.Find \n4.Insert at given position \n5.Delete \n");
scanf ("%d", &choice);
if (choice == 1) {
int data;
scanf ("%d", &data);
insert (data, start);
printf ("Start inside while : %d \n", start);
}
if (choice == 2) {
print (start->next);
printf ("\n");
}
if (choice == 3) {
int fin;
scanf ("%d", &fin);
if (find (fin, start) == 1)
printf ("Found \n");
else
printf ("Not Found \n");
}
if (choice == 4) {
int ins;
scanf ("%d", &ins);
int x;
scanf ("%d", &x);
q = findp (x, start);
insertp (ins, q);
}
}
}

void insert (int x, node * p)
{
while (p->next != NULL)
p = p->next;
p->next = (node *) malloc (sizeof (node));
p = p->next;
p->elt = x;
p->next = NULL;
printf ("P : %d \n", p);
}

void print (node * q)
{
if (q == NULL) {
return;
}
printf ("%d ", q->elt);
print (q->next);
}

int find (int x, node * p)
{
while (p != NULL) {
if (p->elt == x)
return 1;
p = p->next;
}
return 0;
}

void insertp (int x, node * p)
{
node *tmpcell = (node *) malloc (sizeof (node));
tmpcell->elt = x;
tmpcell->next = p->next;
p->next = tmpcell;
}

node *findp (int x, node * p)
{
while (p != NULL && p->elt != x)
p = p->next;
return p;
}

最佳答案

要更改 start 的值,您必须将 start 的地址传递给插入函数并将其修改为如下所示。只有这样,start 的值才会在每次插入时发生变化。

void insert(int x,node **p)
{
while((*p)->next!=NULL)
(*p)=(*p)->next;
(*p)->next=(node *)malloc(sizeof(node));
(*p)=(*p)->next;
(*p)->elt=x;
(*p)->next=NULL;
printf("P : %d \n",p);
}

关于c - C 参数值中的单链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38642332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com