您的位置:首页 > 其它

不带头结点的链表实现

2013-08-18 18:51 330 查看
#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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: