c语言 链表插入

来源:互联网 发布:linux 用户密码修改 编辑:程序博客网 时间:2024/05/22 05:02

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

typedef struct Node{
    int data;
    struct Node *next;
}No;
int Add(No *head,int n);

int main()
{
    No *head;      //头指针
    int array[10]={0,1,2,3,4,5,6,7,8,9};
    head=(No*)malloc(sizeof(No));
    No *p=head;
    No *q=head;
    int i=0;
    for(;i<10;i++)
    {                             //创建下一个节点时,要先为该节点分配存储空间,然后才能用上一个节点指向下一个节点
        head->data=array[i];
        head->next=(No*)malloc(sizeof(No));
        head=head->next;
    }
    head->next=NULL;        //尾指针为空
    Add(q,5);
    while(p->next!=NULL)
    {
        printf("    %d",p->data);
        p=p->next;
    }
    return 1;
}

int Add(No *head,int n)
{
    No * p=head,*after,*newone;
    while(p->data!=n)
    {
        p=p->next;
    }
    after=p->next;
    newone=(No*)malloc(sizeof(No));
    scanf("%d",&newone->data);
    newone->next=after;
    p->next=newone;
    return 1;
}

原创粉丝点击