带有头结点的链表实现

不带头结点的链表,其插入和删除节点操作需要分两种讨论:第一个数据节点 和 非第一个数据节点。


加入了一个不含数据项的头结点可以统一这两个操作,使得插入和删除可以统一实现,避免了分情况讨论。


#ifndef LIST2_H_INCLUDED

#define LIST2_H_INCLUDED


typedef int ElemType;


struct node
{
    ElemType data;
    struct node*next;
};


struct node* InitialList(struct node*head)/*链表的初始化*/
{
    head = (struct node*)malloc(sizeof(struct node));
    head -> next = NULL;
    return head;
}


int length(struct node*head)
{
    int len=0;
    for(len=0;head->next;head=head->next) len++;
    return len;
}


struct node*Insert(struct node*head,int position,ElemType x)
{
    if(position<1||position>length(head)+1)
    {
        printf("illegal position.\n");
        return head;
    }


    int k;
    struct node*p=head;
    struct node*tmp=(struct node*)malloc(sizeof(struct node));
    tmp->data = x;
    for(k=1;k<position;k++) p=p->next;


    tmp->next = p->next;
    p->next = tmp;
    return head;
}


void Print(struct node*head)
{
    if(head->next==NULL) printf("List is empty.\n");
    else printf("List has %d elements.They are:\t",length(head));


    while(head->next)
    {
        printf("%d\t",head->next->data);
        head = head->next;
    }
    printf("\n");
}


struct node*DelNode(struct node*head,ElemType x)
{
    if(head->next==NULL)
    {
        printf("Can't Delete.List is empty.\n");
        return head;
    }


    struct node*p,*tmp;
    for(p=head;p->next;p=p->next)
    {
        if(p->next->data==x) break;
    }
    if(p->next==NULL) //未找到
    {
        printf("No this Element.\n");
        return head;
    }


    tmp = p->next;
    p->next = tmp->next;
    free(tmp);
    return head;


}




#endif // LIST2_H_INCLUDED
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值