双向带头循环链表的应用

struct node{
	int data;
	struct node*next;
	struct node*prev;
};
任意位置插入节点,会插入在给点节点的前面
void insert(struct node*pos,int x){
	struct node*node=(struct ListNode*)malloc(sizeof(struct ListNode));
	node->data=x;
	node->next=NULL;
	struct node*prev=pos->prev;
	struct node*next=pos->next;
	prev->next=node;
	node->prev=prev;
	node->next=next;
	next->prev=node;
}
删除任意位置的结点
void erase(struct node*pos){
	node*prev=pos->prev;
	node*next=pos->next;
	prev->next=next;
	next->prev=prev;
	free(pos);
}
销毁链表,但是头是无法销毁的,必须用二级指针
void destory(struct node*head){
	struct node*cur=head->next;
	while(cur!=head){
		struct node*next=cur->next;
		free(cur);
		cur=next;
	}
}
void pushfront(struct node*head,int x){
	struct node*node=(struct node*)malloc(sizeof(struct node));
	node->data=x;
	node->next=NULL;
    struct node*next=head->next;
    head->next=node;
    node->prev=head;
    node->next=next;
    next->prev=node;
}
void pushback(struct node*head,int x){
	struct node*tail=head->prev;
	struct node*node=(struct node*)malloc(sizeof(struct node));
	node->data=x;
	node->next=NULL;
	tail->next=node;
	node->prev=tail;
	node->next=head;
	head->prev=node;
}
void popfront(struct node*head){
	struct node*first=head->next;
	struct node*second=first->next;
    head->next=second;
    second->prev=head;
}
void popback(struct node*head){
	struct node*tail=head->prev;
	struct node*prev=tail->prev;
	free(tail);
	head->prev=prev;
	prev->next=head;
}

你可能感兴趣的:(链表,数据结构,算法)