参数C值中的单链表

时间:2016-07-28 16:48:05

标签: c data-structures linked-list

我在这方面有点新手。只是想问为什么开始不改变的价值,但是每次连续调用时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;
}

1 个答案:

答案 0 :(得分:0)

对于开始更改的值,您必须将start的地址传递给insert函数并将其修改为如下所示。只有这样,每次插入时,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); 
}