链表指针作为函数参数的传递


#include//无头节点 
#include
typedef struct List
{
    int val;
    struct List *next;
}list;
void a(list*pst)
{
    pst=pst->next;
}
int main()
{
    list *head,*last,*p;
    head=NULL;
    int i,n;
    scanf("%d",&n);
    for(i=0;imalloc(sizeof(struct List));
        scanf("%d",&(p->val));
        if(head==NULL)
        {
            head=p;
            last=head;
        }
        else
        {
            last->next=p;
            last=p;
            last->next=NULL; 
        }
    }
    a(head);
    while(head)
    {
        printf("%d ",head->val);
        head=head->next;
    }
}

创建一个单向链表,把头指针head传递给函数a,a的作用是使头指针指向下一节点,为什么a没起到理想的作用

原来函数的写法里,void a(list*pst) 函数形参 *pst 的作用域只在函数体内部,当函数执行完毕,这个指针变量*pst 也就释放销毁了,对主函数里调用的实参没有影响,失去了作用。修改如下,供参考:

#include<stdio.h>//无头节点 
#include<stdlib.h>
typedef struct List
{
    int val;
    struct List* next;
}list;
list* a(list* pst)   //void a(list* pst)  修改
{
    pst = pst->next;
    return pst;      //修改 
}
int main()
{
    list* head, * last, * p;
    head = NULL;
    int i, n;
    scanf("%d", &n);
    for (i = 0; i < n; i++)
    {
        p = (list*)malloc(sizeof(struct List));
        scanf("%d", &(p->val));
        if (head == NULL)
        {
            head = p;
            last = head;
        }
        else
        {
            last->next = p;
            last = p;
            last->next = NULL;
        }
    }
    //a(head);  //修改
    p = head;   //修改
    while (p)
    {
        printf("%d ", p->val);
        //head = head->next;    //修改
        p = a(p);               //修改
    }
}

void a(list **pst)
函数中改变指针指向需要传递指针的指针。