当前位置:网站首页>C语言_双创建、前插,尾插,遍历,删除

C语言_双创建、前插,尾插,遍历,删除

2022-07-06 06:36:00 Mr_WangAndy

C语言实现双链表的基本操作:创建,前插,后插,遍历,删除


#include <stdio.h>
#include <stdlib.h>

typedef struct node
{
    
	int data;
	struct node *pPre;
	struct node *pNext;
}Node;
// 创建节点
Node *create_node(int data)
{
    
	Node *p = (Node *)malloc(sizeof(Node));
	if (NULL == p)
	{
    
		return NULL;
	}
	// 
	p->pPre = NULL;
	p->data = data;
	p->pNext = NULL;
	return p;
}

// 双链表尾插
int insert_tail(Node *pH,Node *new)
{
    
	if(pH == NULL)
	{
    
		return -1;
	}
	Node *p = pH;
	int cout = 0;
	while(p->pNext)
	{
    
		p = p -> pNext;
		cout++;
	}
	p->pNext = new; // next指针关联
	new->pPre = p;	// pre指针关联
	pH->data = cout + 1;
	return 0;
}

// 前插
int insert_forward(Node *pH,Node *new)
{
    
	if(pH == NULL)
	{
    
		return -1;
	}
	static int cout = 0;
	// 判断头节点后边是否有节点
	if (pH->pNext == NULL)
	{
    
		pH->pNext = new;
		new->pPre = pH;
		cout++;
	}
	else
	{
    
		new->pNext = pH->pNext;
		new->pPre = pH;
		pH->pNext->pPre = new;
		pH->pNext = new;
		cout++;
	}
	pH->data = cout;
	return 0;
}

// 遍历
void traversal_dlink(Node *pH)
{
    
	Node *p = pH;
	printf("向后遍历\n");
	while (p->pNext)
	{
    
		p = p->pNext;
		printf("data=%d.\n",p->data);
	}
	// 再向前遍历
	printf("向前遍历\n");
	while (p->pPre)
	{
    
		printf("data=%d.\n",p->data);
		p = p->pPre;
	}
	
}

// 删除节点 
int delete_node(Node *pH,int data)
{
    
	Node *p = pH;
	
	if (NULL == pH || NULL == pH->pNext)
	{
    
		
		return -1;
	}
	while (NULL != p->pNext)
	{
    
		p = p->pNext;
		if (p->data == data)
		{
    
			// 如果最后一个是节点
			if (p->pNext != NULL)
			{
    
				p->pPre->pNext = p->pNext;
				p->pNext->pPre = p->pPre;
				free(p);
			}
			else
			{
    
				p->pPre->pNext = NULL;
				free(p);
			}
			
			// 如果不是最后一个节点
			return 0;
		}
	}
	
}

int main()
{
    
	Node *pHeader = create_node(0);
	insert_forward(pHeader,create_node(101));
	insert_forward(pHeader,create_node(102));
	insert_forward(pHeader,create_node(103));
	insert_forward(pHeader,create_node(104));
	insert_forward(pHeader,create_node(105));
	// 遍历
	traversal_dlink(pHeader);
	delete_node(pHeader,101);
	traversal_dlink(pHeader);
	return 0;
	
	
}

在这里插入图片描述

原网站

版权声明
本文为[Mr_WangAndy]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_43916755/article/details/125581706