不带头结点的链表实现

#ifndef LIST_H_INCLUDED
#define LIST_H_INCLUDED


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


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


struct node* Insert(struct node*head,int n,int x)   //向L中插入e 在位置i
{
    if (n<1||n>length(head)+1)
    {
        printf("Position is illegal.\n");    //位置不合法
        return head;
    }


    struct node * newnode=(struct node*)malloc(sizeof(struct node));
    newnode->data=x;


    if (n==1)//头结点插入的情况
    {
        newnode->next = head;
        head = newnode;
        return head;
    }


    int i;
    struct node*p=head;


    for (i=2;i<n;i++) p=p->next;/* head指向的是第二个节点的前驱节点   为了找前驱 */
    newnode->next=p->next;
    p->next=newnode;
    return head;


}


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


struct node*DelNode(struct node*head,int x)//无非就是找到前驱 然后记录 删除 free
{
    if(head==NULL) {printf("Can't delete .List is empty.\n");return head;}
    struct node*p,*pre;
    for(p=head;p!=NULL;pre=p,p=p->next)//还是引用值之前未先判断空
    {
        if(p->data==x) break;
    }
    if(p==NULL) {printf("No this data.\n");return head;}


    if(p==head) {head=head->next;free(p);}
    else
    {
        pre->next=p->next;
        free(p);
    }
    return head;
}


int Elem(struct node*head,int position)
{
    if(position<1||position>length(head))
    {
        printf("illegal position.\n");
        exit(0);
    }


    int k;
    for(k=1;k<position;k++) head = head->next;
    return head->data;
}


int Locate(struct node*head,int x)
{
    int k;
    for(k=0;head;head=head->next,k++)
    {
        if(head->data==x) return k;
    }
    return 0;
}


#endif // LIST_H_INCLUDED
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值