簡體   English   中英

參數的C值中的單鏈表

[英]Single Linked List in C value of parameter

我對此有點新手。 只是想問一下為什么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 change的值,您將必須將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); 
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM