带头双向循环链表基础

带头双向循环链表基础

销毁

//销毁
void ListDestory(ListNode* phead);
void ListDestory(ListNode* phead) {
	assert(phead);
	ListNode* cur = phead->next;
	while (cur != phead) {
		ListNode* next = cur->next;
		free(cur);
		cur = next;
	}
	free(phead);
	phead = NULL;
}

 

 尾插

//尾插
void ListPushBack(ListNode* phead, LTDataType x);
//尾插
void ListPushBack(ListNode* phead, LTDataType x) {
	assert(phead);

	/*ListNode* tail = phead->prev;
	ListNode* newnode = BuyListNode(x);
	tail->next = newnode;
	newnode->prev = tail;
	newnode->next = phead;
	phead->prev = newnode;*/
	ListInsert(phead, x);
}

 

 头插

//头插
void ListPushFront(ListNode* phead, LTDataType x);
//头插
void ListPushFront(ListNode* phead, LTDataType x) {
	//ListNode* first = phead->next;
	//ListNode* newnode = BuyListNode(x);
	///*phead->next = newnode;
	//newnode->prev = phead;
	//newnode->next = first;
	//first->prev = newnode;*/
	//newnode->next = phead->next;
	//phead->next->prev = newnode;
	//phead->next = newnode;
	//newnode->prev = phead;
	ListInsert(phead->next,x);
}

 

尾删 

//尾删
void ListPopBack(ListNode* phead);
//尾删
void ListPopBack(ListNode* phead) {
	/*assert(phead);
	assert(phead->next != phead);
	ListNode* tail = phead->prev;
	ListNode* prev = tail->prev;
	phead->prev = prev;
	prev->next = phead;
	free(tail);
	tail = NULL;*/
	ListErase(phead->prev);
}

 

头删 

//头删
void ListPopFront(ListNode* phead);
//头删
void ListPopFront(ListNode* phead) {
	/*assert(phead);
	assert(phead->next != phead);
	ListNode* first = phead->next;
	ListNode* second = first->next;
	phead->next = second;
	second->prev = phead;
	free(first);
	first = NULL;*/
	ListErase(phead->next);
}

 

打印 

打印
void ListPrint(ListNode* phead);
void ListPrint(ListNode* phead) {
	ListNode* cur = phead->next;
	while (cur!=phead) {
		printf("%d  ", cur->data);
        cur = cur->next;
	}
	printf("NULL\n");
}

 

 查找

查找
ListNode* ListFind(ListNode* phead, LTDataType x);
ListNode* ListFind(ListNode* phead, LTDataType x) {
	assert(phead);
	ListNode* cur = phead->next;
	while (cur != phead) {
		if (cur->data == x) {
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

 

pos位置前插入x 

//pos位置前插入x
void ListInsert(ListNode* pos, LTDataType x);

 

void ListInsert(ListNode* pos, LTDataType x) {
	assert(pos);
	ListNode* prev = pos->prev;
	ListNode* newnode = BuyListNode(x);
	prev->next = newnode;
    newnode->prev = prev;
	newnode->next = pos;
	pos->prev = newnode;
}

删除pos位置的值 

//删除pos位置的值
void ListErase(ListNode* pos);
void ListErase(ListNode* pos) {
	ListNode* prev = pos->prev;
	ListNode* next = pos->next;
	prev->next = next;
	next->prev = prev;
}

你可能感兴趣的:(链表,数据结构,c语言)