1 #include <iostream> 2 using namespace std; 3 typedef struct DulNode 4 { 5 int data; 6 struct DulNode *next; //后继节点 7 struct DulNode *prior; //前驱节点 8 }DulNode,*DulLinkList; 9 10 11 void Creat_DLink(DulLinkList &L) //尾插法创建单链表 12 { 13 L = new DulNode; 14 L->next=NULL; //先建立一个带头结点的空链表 15 DulLinkList p=L; //中间变量 16 int n; 17 cout<<"1)你想输入多少数字?:"; 18 cin>>n; 19 cout<<"请输入表数据,以空格隔开:"; 20 for(int i = 0;i<n;++i) 21 { 22 DulLinkList s = new DulNode; //中间变量 23 cin>>s->data; //将输入元素的值赋给s 24 s->next=NULL; //将新节点插入到头节点之后 25 p->next=s; 26 s->prior=p; 27 p=s; 28 } 29 cout<<"建表成功\n2)链表为:"; 30 } 31 32 DulNode *GetElem(DulLinkList L,int i) //取得第i个位置的位置指针p 33 { 34 DulLinkList p = new DulNode; 35 p=L->next; 36 int j=1; 37 while(p&&j<i) { 38 p = p->next; 39 ++j; 40 } 41 return p; 42 } 43 44 int Insert_DulLink(DulLinkList &L,int i,int e) //插入 45 { 46 DulLinkList p=new DulNode; 47 DulLinkList s=new DulNode; 48 p=GetElem(L,i); 49 if(!p) 50 return -1; 51 s->data = e; 52 s->next = p->next; p->next = s; 53 s->next->prior = s; s->prior = p; 54 return 0; 55 56 } 57 58 int Delete_DulLink(DulLinkList &L,int i) //删除 59 { 60 DulLinkList p=new DulNode; 61 p=GetElem(L,i); 62 if(!p) 63 return -1; 64 p->prior->next=p->next; 65 p->next->prior=p->prior; 66 delete p; 67 cout<<"删除成功\n"; 68 return 0; 69 } 70 71 void Print_DLink(DulLinkList L) //输出 72 { 73 DulLinkList p=L->next; 74 while(p) { 75 cout<<p->data<<" "; 76 p=p->next; 77 } 78 cout<<endl; 79 } 80 81 int main() 82 { 83 DulLinkList L; 84 int a,b; 85 Creat_DLink(L); 86 Print_DLink(L); 87 cout<<"3)请输入要插入的位置和数值:"; 88 cin>>a>>b; 89 Insert_DulLink(L,a,b); 90 cout<<"插入后链表为:"; 91 Print_DLink(L); 92 int i; 93 cout<<"4)请输入要删除的位置:"; 94 cin>>i; 95 Delete_DulLink(L,i); 96 cout<<"删除后链表为:"; 97 Print_DLink(L); 98 return 0; 99 }
编译结果如下:
原文地址:https://www.cnblogs.com/DSYR/p/9190686.html
时间: 2024-10-22 15:33:51