双向链表的基本操作

双链表


表现形式:

指针域(指向前驱)数据域指针域(指向后边)

c语言中结构体的定义的模板:

1  struct 类型名{
2      成员表列
3  } 变量;

在C语言中,双向链表中结点的结构体如下所示:

 
1 struct node    
2  {    
3      struct node *prev;       
4      int data;      
5      struct node *next; 
6 7   }
8  
 ​

双链表的基本操作:

  1. 建立双向链表

 

 1 dlink *credlink(void)  // -1 结束
 2 { 
 3   dlink *head,*p,*s; 
 4   ElemType x;
 5   p=head=(dlink *)malloc(sizeof(dlink));    // C语言中malloc是动态内存分配函数。
 6     //菜鸟教程文档
 7     //https://www.runoob.com/cprogramming/c-function-malloc.html
 8   scanf("%d",&x);
 9   while(x!=-1)
10   { 
11         s=(dlink *)malloc(sizeof(dlink));
12         s->data=x;
13         p->next=s; s->prior=p;
14         p=s;
15         scanf("%d",&x);
16   }
17   p->next=head->prior=NULL;
18     /*
19     
20     
21     */
22   return head;
23 }

 

 

 

  2. 进行输出操作

 

 1 void list(dlink *head)
 2 {
 3   dlink *p;
 4   p=head;
 5   while(p->next)  // 输出之后将p 指针停在尾结点上
 6   { 
 7         p=p->next;
 8      printf("%5d",p->data);
 9   }
10   printf("\n");
11   while(p!=head)
12   { 
13      printf("%5d",p->data);
14      p=p->prior;
15   }
16   printf("\n");
17 }

 

 

 

  3. 插入(在第i个结点前插入一个值为x的结点)

 

 1 int insert(dlink *head,int i,ElemType x)
 2 { 
 3   dlink *p,*s; int j;
 4   if(i<1) 
 5       return 0;
 6   p=head;j=0;
 7   while(p&&j<i-1)
 8   { 
 9       p=p->next; j++;
10   }
11   if(!p)
12       return 0;
13   s=(dlink *)malloc(sizeof(dlink));
14   s->data=x;
15   s->next=p->next;  s->prior=p;
16   if(p->next) 
17       p->next->prior=s;
18         p->next=s;
19       return 1;
20 }

 

 

 

  4. 删除

 

 1 int deli(dlink *head,int i,ElemType *e)
 2 { 
 3     dlink *p; int j;
 4   if(i<1)
 5       return 0;
 6       p=head->next; j=1;
 7   while(p&&j<i)
 8   { 
 9       p=p->next;j++;
10   }
11   if(!p) 
12       return 0;
13   if(p->next)
14     p->next->prior=p->prior;
15       p->prior->next=p->next;
16     *e=p->data;
17     free(p);
18   return 1;
19 }

 

 

 一些常用示例 

  1. 将双链表逆置

  

 1 void invert(dlink *head)
 2 {
 3 dlink *p,*q; ElemType x;
 4 for(p=head->next,q=head;q->next;q=q->next);
 5 while(p!=q&&q->next!=p)
 6 {
 7 t=p->data;
 8 p->data=q->data;
 9 q->data=t;
10 p=p->next;
11 q=q->prior;
12 }
13 }

  2. 编写算法,判断一个双链表是否前后对称。

 

 1 int issymmetry(dlink *head)
 2 { 
 3     dlink *p,*q; 
 4   for(p=head->next,q=head;q->next;q=q->next);
 5   while(p!=q&&q->next!=p)
 6   { 
 7       if(p->data!=q->data) 
 8           return 0;
 9     p=p->next; q=q->prior;
10   }
11   return 1;
12 }

 

 

 

  3. 编写算法,将两个双向链表首尾连接成一个双链

 

 1 void connect(dlink *ha,dlink *hb)
 2 { 
 3     dlink *p;
 4   for(p=ha; p->next; p=p->next);
 5   if(hb->next)
 6 { 
 7       p->next=hb->next;
 8     hb->next->prior=p;
 9   }
10 free(hb);
11 }

 

  

    刚刚接触数据结构,如有错误还望各位大佬斧正!谢谢各位!

 

posted @ 2022-09-08 17:59  代码改变世界—北枳  阅读(79)  评论(0)    收藏  举报