编程实现双链表的建立、插入、删除

#include <iostream>
#include <stdio.h>
#include <malloc.h>

using namespace std;

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

node *creat(){//双链表创建
    node *head,*p,*s;
    int x,cycle=1;
    head=(node *)malloc(sizeof(node));
    p=head;
    while(cycle){
        cout<<"please input the data:";
        cin>>x;
        if(x!=0){
            s=(node *)malloc(sizeof(node));
            s->data=x;
            p->next=s;
            s->pre=p;
            p=s;
        }
        else
            cycle=0;
    }
    p->next=NULL;
    p=head;
    head=head->next;
    free(p);
    head->pre=NULL;
    return head;
}

node *del(node *head, int num){//双链表删除
    node *p1,p2;
    p1=head;
    while(p1->data!=num&&p1->next!=NULL){
        p1=p1->next;
    }
    if(num==p1->data){
        if(p1==head){
            head=p1->next;
            head->pre=NULL;
            free(p1);
        }
        else if(p1->next==NULL){
            p1->pre->next=NULL;
            free(p1);
        }
        else{
            p1->pre->next=p1->next;
            p1->next->pre=p1->pre;
            free(p1);
        }
    }
    else
        cout<<"can not find "<<num;
    return head;
}

node *insert(node *head, int num){//插入链表--插入到第一个不小于num之后
    node *p1,*p2;
    p1=head;
    p2=(node*)malloc(sizeof(node));
    p2->data=num;
    while(p2->data>p1->data&&p1->next!=NULL){
        p1=p1->next;
    }
    if(p2->data<=p1->data){
        if(p1==head){
            p2->next=head;
            p2->pre=NULL;
            head=p2;
        }
        else{
            p2->next=p1->next;
            p1->next->pre=p2;
            p1->next=p2;
            p2->pre=p1;
        }
    }
    else{
            p2->next=NULL;
            p2->pre=p1;
            p1->next=p2;
        }
    return head;
}

int main(){
    node *head;
    int n,del_num,insert_num;
    head=creat();
    cout<<"头结点数值:"<<head->data;
    cout<<"\n delete_num:";
    cin>>del_num;
    head=del(head,del_num);
    cout<<"头结点数值:"<<head->data;
    cout<<"\n insert_num:";
    cin>>insert_num;
    head=insert(head,insert_num);
    cout<<"头结点数值:"<<head->data;
    return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值