#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;
}
编程实现双链表的建立、插入、删除
最新推荐文章于 2022-09-25 13:47:37 发布