双向链表的插入与删除

#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
#define OK 1
#define ERROR 0
#include<string.h>
typedef struct Node
{ int data;
  struct Node *pre,*next;
	
 }Node,*DoubleList;
 
 
 
Node* create(int x) 
 {
 	Node *L,*s,*r;
 	int temp,i;
 	L=(Node*)malloc(sizeof(Node));
 	L->next=NULL;
 	r=L;
   for(i=1;i<=x;i++)
 	{       scanf("%d",&temp);
 			s=(Node*)malloc(sizeof(Node));
 			s->data=temp;
 		    r->next=s;
			r=s;
	 }
     r->next=NULL;
	 return L;
 }
 
Node* Insert(Node* &L,int pos,int x)
{  Node *p=L;
Node *s;
   int k=0;
   while(p!=NULL&&k<pos-1)
	{
		p=p->next;
		k++;
	}
	if(k!=pos-1)
	{
	printf("插入位置错误"); 
	   return L;}
	
s=(Node*)malloc(sizeof(Node));
s->data=x;
s->pre=p;   //要考虑在末尾插入时,p已经是NULL!!!不能有p->next->pre
s->next=p->next;
p->next=s;
return L;
}



Node* Delete(Node* &L,int pos) 
 {
 	Node *s,*p;
 	int k;
 	p=L;
 	while(p->next!=NULL&&k<pos)
 	{
 		p=p->next;
 		k++;
	 }
	 
	 if(k!=pos||pos==0)
	{
	printf("删除位置错误");
	   return L;
	   }
	 p->pre->next=p->next;
	 // //要考虑在末尾删除时,p已经是NULL!!!不能有p->next->pre
	
 	return L;
 }
 
 
 void show(Node* L)
{  Node *p;
   p=L->next;
	while(p!=NULL)
	{
		printf("%d ",p->data);
		p=p->next;
	}
	printf("\n");
}
 int main()
 {
 	int a,pos,x,y;
 	Node *L1;
 	printf("链表的长度:");
 	scanf("%d",&a);
 	L1=create(a);
 	printf("插入的位置以及数值:");
 	scanf("%d%d",&pos,&x);
 	L1=Insert(L1,pos,x);
 	show(L1);
 	printf("输入删除的位置:");
 	scanf("%d",&y);
 	L1=Delete(L1,y);
    show(L1);
 	
 	
 }

猜你喜欢

转载自blog.csdn.net/weixin_43913556/article/details/88536187