双向链表 建立和插入

        单链表有next指针,在查询下一个结点的时间复杂度为O(1),但在查询上一个结点时就会很麻烦,因为每次只能从头指针head开始遍历查找。双向链表就克服了这个缺点。


        双向链表定义:双向链表是在单链表的每个结点中,再设置一个指向其前驱结点的指针域。所以双向链表的每个结点都有两个指针域,分别指向前后结点。


        双向链表特点:
  1.每次在插入或删除某个节点时, 需要处理四个节点的引用, 而不是两个. 实现起来要困难些;
  2.相对于单向链表, 必然占用内存空间更大一些;
  3.既可以从头遍历到尾, 又可以从尾遍历到头。


-定义结构体-

typedef struct node{
	int data;
	struct node *pre;
	struct node *next;
}Node,*linklist;

-初始化链表-

Node *CreatNode(Node *head)
{
        head=(Node*)malloc(sizeof(Node));
        if(head == NULL)
        {
            printf("malloc error!\r\n");
            return NULL;
        }
        head->pre=NULL;
        head->next=NULL;
        return head;
}

-建立链表-

Node* CreatList(Node * head,int length)
{
    if (length == 1)
    {
        
        return( head = CreatNode(head));
    }
    else
    {
        head = CreatNode(head);
        Node * list=head;
        for (int i=1; i<length; i++) 
        {
            Node * body=(Node*)malloc(sizeof(Node));
            body->pre=NULL;
            body->next=NULL;
            body->data=rand()%MAX;
            list->next=body;
            body->pre=list;
            list=list->next;
        }
    }
    return head;
}

-双向链表的插入-

双向链表的指针较多,插入时要调整的指针也就更多

例如要将s结点插入在链表的p和第p -> next中间,需要以下四步:

1.把p赋值给s的前驱

2.把p -> next赋值给s的后继

3.把s赋值给p ->next的前驱

4.把s赋值给p的后继

void InsertElem( linklist head , int data ){
	linklist tmpHead = head;		//  创建一个临时的头结点指针
	if( tmpHead->next == NULL ){
		/*  当双向链表只有一个头结点时 */		
		linklist addition = (linklist)malloc( sizeof(linklist) );
		assert( addition != NULL );
		addition -> data = data;
		addition -> next = tmpHead->next;
		tmpHead -> next = addition;
		addition -> front = tmpHead;
	}
	else{
		/* 当双向链表不只一个头结点时 */
		linklist addition = (pElem)malloc( sizeof(linklist) );
		assert( addition != NULL );
		addition -> data = data;
		tmpHead -> next->front = addition;
		addition -> front = tmpHead;
		addition -> next = tmpHead->next;
		tmpHead -> next = addtion;
	}
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值