C语言19

本文介绍了三种基础数据结构——双向链表、队列和栈的实现。通过C语言代码展示了如何创建、插入和删除节点,以及它们在实际问题中的应用。双向链表允许从两端访问节点,队列遵循先进先出原则,而栈则遵循先进后出原则。这些基础知识对于理解和解决计算机科学中的问题至关重要。
摘要由CSDN通过智能技术生成

双向链表

#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
	int id;
	struct Node* pNext;
	struct Node* pLast;
}List;
void AddNode(List** ppHead,List** ppEnd,int id)
{
	List* pTemp = (List*)malloc(sizeof(List));

	pTemp->id = id;
	pTemp->pLast = NULL;
	pTemp->pNext = NULL;

	//判断链表中是否有节点
	   //没有
	   //头指针指向新来的节点
	   //尾指针指向新来的节点
	if (*ppHead == NULL)
	{
		*ppHead = pTemp;
		*ppEnd = pTemp;
	}
	else
	{
		(*ppEnd)->pNext = pTemp;
		pTemp->pLast = *ppEnd;
		*ppEnd = pTemp;
	}
     
	   //有
	   //尾节点的下一个指向新来的节点
	   //新来节点的上一个指向尾节点
	   //尾指针指向新来的节点
}




int main()
{
	List* pHead = NULL;
	List* pEnd = NULL;

	AddNode(&pHead, &pEnd, 1);
	AddNode(&pHead, &pEnd, 2);
	AddNode(&pHead, &pEnd, 3);
	AddNode(&pHead, &pEnd, 4);


	return 0;
}

队列

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

//队列 queue 先进先出
typedef struct Node
{
	int value;
	struct Node* pNext;

}Queue;

void Q_Push(Queue** ppHead,Queue** ppTail,int n)
{
	Queue* pTemp = (Queue*)malloc(sizeof(Queue));
	pTemp->value = n;
	pTemp->pNext = NULL;
	if (*ppHead == NULL)
	{
		*ppHead = pTemp;
	}
	else
	{
		(*ppTail)->pNext = pTemp;
	}
	*ppTail = pTemp;
}
Queue* Q_Pop(Queue**ppHead,Queue**ppTail)
{
	if (NULL == ppHead || NULL == *ppHead)
	{
		return NULL;
	}
	Queue* pMark = NULL;
	pMark = *ppHead;
	*ppHead = (*ppHead)->pNext;
	if (pMark->pNext == NULL)
	{
		*ppTail = NULL;
	}
	return pMark;
}

int main()
{
	Queue* pHead = NULL;
	Queue* pTail = NULL;

	Q_Push(&pHead, &pTail, 1);
	Q_Push(&pHead, &pTail, 2);
	Q_Push(&pHead, &pTail, 3);
	Q_Push(&pHead, &pTail, 4);
	printf("%d\n", Q_Pop(&pHead, &pTail)->value);
	printf("%d\n", Q_Pop(&pHead, &pTail)->value);
	printf("%d\n", Q_Pop(&pHead, &pTail)->value);
	printf("%d\n", Q_Pop(&pHead, &pTail)->value);

	return 0;
}

#include<stdio.h>
#include<stdlib.h>
//栈 stack 先进后出

typedef struct Node
{
	int value;
	struct Node* pNext;
}Stack;
void S_Push(Stack** ppTop, int n)
{
	Stack* pTemp = (Stack*)malloc(sizeof(Stack));
	pTemp->value = n;
	pTemp->pNext = NULL;
	/*if (*ppTop == NULL)
	{
		*ppTop = pTemp;
	}*/
	/*else
	{*/
		pTemp->pNext = *ppTop;
		*ppTop = pTemp;
	/*}*/
}
int S_Pop(Stack** ppTop)
{
	Stack* pMark = NULL;
	int value;
	if (ppTop == NULL || *ppTop == NULL)
	{
		return -1;
	}
	pMark = *ppTop;
	*ppTop = (*ppTop)->pNext;
	value = pMark->value;
	free(pMark);
	pMark = NULL;
	return value;
}

int main()
{
	Stack* pTop = NULL;
	
	S_Push(&pTop, 1);
	S_Push(&pTop, 2);
	S_Push(&pTop, 3);
	S_Push(&pTop, 4); 
	printf("%d\n",S_Pop(&pTop));
	printf("%d\n", S_Pop(&pTop));
	printf("%d\n", S_Pop(&pTop));
	printf("%d\n", S_Pop(&pTop));
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值