c - C 参数值中的单链表

标签 c data-structures linked-list

我在这方面有点新手。只是想问为什么 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/

相关文章:

在 Erlang/Elixir 中用多个 png 文件合成 jpeg 图像

c++ - 试图引用已删除的函数、具有互斥成员的结构

c - 链接列表和 fscanf

c - 链接列表程序停止工作错误

C、malloc、free 和自动检查

c - 将字节数组从 NodeJS 发送到 C 库

python - 在需要列表或元组的情况下传递参数时要传递什么?

抛出 NoSuchElementException 的 Java Arraylist 程序

c++ - 列表循环检测

c - 嵌入式 C 中的 FIFO 队列 - 计数器会溢出吗?