双向链表-插入元素

不会写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;
} 


猜你喜欢

转载自blog.csdn.net/WJHKDGHP/article/details/78766245