指针复习之单链表实现

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
typedef struct node
{
    int data;
    struct node *next;
} node;
node *init()
{
    node *head;
    head=(node*)malloc(sizeof(node));
    head->next=NULL;
    return head;
}
void display(node *head)
{
    node *p;
    p=head->next;
    if(!p)
        printf("该头节点所指向的单链表为空");
    else
    {
        while(p)
        {
            printf("%d\n",p->data);
            p=p->next;
        }
    }
}
node *find(node *head,int i)
{
    node *p=head;
    int j=0;
    if(i<0)
    {
        printf("该链表中不存在第%d个节点\n",i);
        return NULL;
    }
    else if(i==0)
        return p;
    while(p&&i!=j)
    {
        p=p->next;
        j++;
    }
    return p;
}
node *insert(node *head,int data,int i)
{
    node *p,*q;
    q=find(head,i);
    if(q==NULL)
    {
        printf("不能插入第%d个数据:%d\n",i,data);
        return head;
    }
    p=(node*)malloc(sizeof(node));
    p->data=data;
    p->next=head->next;
    head->next=p;
}
node *dele(node *head,int data)
{
    node *p,*pre;
    pre=head;
    p=head->next;
    while(p&&p->data!=data)
    {
        pre=p;
        p=p->next;
    }
    if(pre)
    {
        pre->next=p->next;
        //printf("%d\n",p->data);
        free(p);
        //printf("yes %d\n",p->data);
    }
    return head;
}
int main()
{
    node *head=init();
    int i;
    for(i=0; i<10; i++)
        insert(head,i,i);
    node *d=find(head,3);
    printf("%d %d\n",3,d->data);
    dele(head,3);
    display(head);
    printf("%d %d\n",3,d->data);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值