线性表的链式实现(单链表)——无独立表头的实现

来源:互联网 发布:windows下的dig工具 编辑:程序博客网 时间:2024/05/22 12:20
</pre><pre name="code" class="cpp">//非独立表头的,插入和删除操作均麻烦一些,考虑删掉的是不是表头,是不是插在表头前struct node{    int data;    struct node* next;};struct node* Insert(struct node*head,int element){    struct node* p;    p=(struct node*)malloc(sizeof(struct node));    p->data=element;    p->next=NULL;    if(head==NULL)        head=p;    else if(head->data>p->data){//插到头节点前        p->next=head->next;        head=p;    }    else{        struct node* t;        t=head;        while(t->next!=NULL&&t->next->data<=element)//相同的,插到后面            t=t->next;        p->next=t->next;        t->next=p;    }    return head;}//插入另一种方法/*struct node* Insert(struct node*head,int element){    struct node* p;    p=(struct node*)malloc(sizeof(struct node));    p->data=element;    p->next=NULL;    if(head==NULL)        head=p;    else{        struct node* t;        struct node* m;        t=head;        while(t->next!=NULL&&t->next->data<=element){            m=t;            t=t->next;        }        if(element<=t->data){//插在t和m之间           if(head==t)//插到头节点前             head=p;           else       //相同的,插到后面,但未尾除外,插在末尾前             m->next=p;           p->next=t;        }        else//插到尾结点后          t->next=p;     return head;}*/struct node* Delete(struct node* head,int element){    struct node* t;    t=head;    if(element==head->data){//删头节点        head=head->next;        free(t);    }    else{        while(t->next!=NULL&&t->next->data!=element)//删第一个element            t=t->next;        if(t->next!=NULL){            struct node* p;            p=t->next;            t->next=t->next->next;            free(p);        }    }    return head;}//删除另一种方法/*struct node* Delete(struct node* head,int element){    struct node* t;    t=head;    if(element==head->data){//删头节点        head=head->next;        free(t);    }    else{//删除所有element        struct node* m;        m=head;        t=head->next;        while(t!=NULL){            if(t->data==element){                m->next=t->next;                free(t);            }            else             m=t;            t=t->next;        }    }    return head;}*/int main(){    //新建表头    struct node* head;    head=NULL;    //Insert one by one 插入不必有序,新插的放到前一个后面    int n;    int number;    for(int i=1;i<=n;i++){        scanf("%d",&number);        struct node* tail;//上一个结构体地址        struct node* p;//当前申请        p=(struct node*)malloc(sizeof(struct node));        p->data=number;        p->next=NULL;        if(head==NULL)            head=p;        else            tail->next=p;        tail=p;    }    //Insert 按照该在的大小位置插入,新建链表也以插入的方式实现    head=Insert(head,10);//以10为例    //Delete    head=Delete(head,10);//以10为例    //Print 遍历    Print(head);}


1 0