当前位置:网站首页>C language_ Double create, pre insert, post insert, traverse, delete

C language_ Double create, pre insert, post insert, traverse, delete

2022-07-06 06:52:00 Mr_ WangAndy

C Language to realize the basic operation of double linked list : establish , forward , Post insertion , Traverse , Delete


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

typedef struct node
{
    
	int data;
	struct node *pPre;
	struct node *pNext;
}Node;
//  Create nodes 
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;
}

//  Double linked list tail insertion 
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 Pointer Association 
	new->pPre = p;	// pre Pointer Association 
	pH->data = cout + 1;
	return 0;
}

//  forward 
int insert_forward(Node *pH,Node *new)
{
    
	if(pH == NULL)
	{
    
		return -1;
	}
	static int cout = 0;
	//  Judge whether there is a node behind the head node 
	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;
}

//  Traverse 
void traversal_dlink(Node *pH)
{
    
	Node *p = pH;
	printf(" Traverse backward \n");
	while (p->pNext)
	{
    
		p = p->pNext;
		printf("data=%d.\n",p->data);
	}
	//  Traverse forward again 
	printf(" Traversal forward \n");
	while (p->pPre)
	{
    
		printf("data=%d.\n",p->data);
		p = p->pPre;
	}
	
}

//  Delete node  
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 the last one is a node 
			if (p->pNext != NULL)
			{
    
				p->pPre->pNext = p->pNext;
				p->pNext->pPre = p->pPre;
				free(p);
			}
			else
			{
    
				p->pPre->pNext = NULL;
				free(p);
			}
			
			//  If it's not the last node 
			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));
	//  Traverse 
	traversal_dlink(pHeader);
	delete_node(pHeader,101);
	traversal_dlink(pHeader);
	return 0;
	
	
}

 Insert picture description here

原网站

版权声明
本文为[Mr_ WangAndy]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060636209256.html