带头双向循环链表基础

发布时间:2024年01月17日

带头双向循环链表基础

销毁

//销毁
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;
}

文章来源:https://blog.csdn.net/2301_77479435/article/details/135659195
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。