双向链表-插入元素

来源:互联网 发布:语音模拟软件 编辑:程序博客网 时间:2024/06/16 00:40

不会写CSDN博客,所以试试

双向链表在一个有序数列中插入一个数,使之依旧有序。

#include<stdio.h>#include<string.h>#include<stdlib.h>#define len sizeof(struct node)#define newp (struct node*) malloc(len)struct node{int num;struct node *next,*pre;};struct node *p1,*head,*temp,*qian,*hou,*tail;int n,x,i;int main(){scanf("%d",&n);p1=newp;p1->pre=NULL;head=p1;for (i=1; i<=n; i++){scanf("%d",&x);p1->num=x;if (i>1){qian->next=p1;p1->pre=qian;}qian=p1;if (i==n) tail=p1; else p1=newp;}tail->next=NULL;scanf("%d",&x);p1=head;int zh=0,zq=0;for (;;){if (p1->num>x) break;if (p1->next==NULL) {zh=1;break;} else p1=p1->next;}temp=newp;temp->num=x;if (zh==0){qian=p1->pre;hou=p1;temp->pre=qian;temp->next=hou;hou->pre=temp;qian->next=temp;}if (zh==1){tail->next=temp;temp->pre=tail;temp->next=NULL;}return 0;}