双向链表的基本操作

双向链表的插入顺序:

双向链表的删除顺序:



#include<stdio.h>  
#include<stdlib.h> 
typedef struct doubleLink  
{  
    int data;  
    struct doubleLink *pre;  
    struct doubleLink *next;  
}dnode;  
  
//建立链表   
dnode* createDLink()  
{  
    dnode *head,*p,*s;  
    int x;  
    head = (dnode*)malloc(sizeof(dnode));  
    p = head;  
    while(1)  
    {  
        printf("please input the data: ");  
        scanf("%d",&x);  
        if(x != 0)  
        {  
            s = (dnode*)malloc(sizeof(dnode));  
            s ->data = x;  
            s-> pre = p;  
            p->next = s;  
            p=s;  
        }  
        else  
            break;  
    }  
    p->next = NULL;  
    head = head ->next;  
    head->pre = NULL;  
    return head;  
}  
  
//顺序、反序打印链表   
void printDLink(dnode *head)  
{  
    dnode *p,*s;  
    p = head;  
    printf(" left to right: \n");  
    while(p)  
    {  
        printf("%d  ",p->data);  
        s = p;  //为了到达链表的末尾 
        p = p->next;  
    }  
    printf("\n right to left: \n");  
    while(s)  
    {  
        printf("%d  ",s->data);  
        s = s->pre;  
    }  
    printf("\n \n");  
}  
  
//删除一个结点   
dnode* deletedNode(dnode *head,int i)  
{  
    dnode *p;  
    p = head;  
    if(p->data == i)  
    {  
        head = p->next;  
        head->pre = NULL;  
        free(p);  
        return head;  
    }  
  
    while(p)  
    {  
        if(p->data == i)  
        {  
            p->pre->next = p->next;  
            p->next->pre = p->pre;  
            free(p);  
            return head;  
        }  
        p = p->next;  
    }  
  
    printf("data not found \n");  
    return head;  
}  
  
//插入一个结点   
dnode* insertdNode(dnode *head,int i)  
{  
    dnode *p,*temp;  
    p = head;  
  
    temp = (dnode*)malloc(sizeof(dnode));  
    temp ->data = i;  
  
    if(i < p->data)  
    {  
        head = temp;  
        head->next = p;  
        head->pre = NULL;  
        p->pre = head;  
        return head;  
    }  
  
    while(p != NULL && i > p->data)  
    {  
       p = p->next;
	}
	if(i < p->data)
	{
		temp ->next = p;
		temp ->pre = p->pre;
		p ->pre->next = temp;
		p ->pre = temp;
		return head;
	}else
	{
		p->next = temp;
		temp ->pre = p;
		temp ->next = NULL;
		return head;
	}
}
  
  
int  main()  
{  
    dnode *head;  
    head = createDLink();  
    printDLink(head);  
  
    head = insertdNode(head,4);
    head = deletedNode(head,3);  
    printDLink(head);  
    return 0;
}  


  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值