面试题5: 链表的相关操作

本文介绍了链表的基本操作,包括在链表末尾添加节点、删除指定节点及逆序输出链表节点的方法。提供了完整的C++实现代码,并通过实例演示了如何进行链表的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.链表的相关操作,在末尾添加节点,删除指定的节点,逆序输出链表的节点。


源码


/*链表的相关操作*/
#include<iostream>
#include<stack>
#include<stdio.h>
using namespace std;

struct ListNode
{
	int value;
	ListNode * pNext;
};

//add node to the tail of the List
void AddToTail(ListNode** pHead, int value)
{
	ListNode* pNew = new ListNode();
	pNew->value = value;
	pNew->pNext = NULL;
	if (*pHead == NULL)
	{
		*pHead = pNew;
		//cout << (*pHead)->value << endl;
	}
	else
	{
		ListNode* pNode = *pHead;
		while (pNode->pNext != NULL)
		{
			pNode = pNode->pNext;
		}
		pNode->pNext = pNew;
	}
}

//remove the node 
void RemoveNode(ListNode** pHead, int value)
{
	if (pHead == NULL || *pHead == NULL)
		return;
	ListNode* pToBeDeleted = NULL;
	ListNode* pNode = *pHead;
	if (pNode->value == value)
	{
		pToBeDeleted = pNode;
		pNode = pNode->pNext;
	}
	else
	{
		while (pNode->pNext != NULL&&pNode->pNext->value != value)
		{
			pNode = pNode->pNext;

		}
		if (pNode->pNext != NULL&&pNode->pNext->value == value)
		{
			pToBeDeleted = pNode->pNext;
			pNode->pNext = pNode->pNext->pNext;
		}
		if (pToBeDeleted != NULL)
		{
			delete pToBeDeleted;
			pToBeDeleted = NULL;
		}
	}
}

//print the node from the head
void PrintFromHead(ListNode** pHead)
{
	int i = 0;
	ListNode* pNode = *pHead;
	while (pNode != NULL)
	{
		cout << "the value of node " << i << ":" << pNode->value << endl;
		pNode = pNode->pNext;
		i++;
	}
}
//print the node from the tail
void PrintFromTail(ListNode** pHead)
{
	int i = 0;
	stack<ListNode*>nodes;
	ListNode* pNode = *pHead;
	while (pNode != NULL)
	{
		nodes.push(pNode);
		pNode = pNode->pNext;
	}
	while (!nodes.empty())
	{
		pNode = nodes.top();
		cout << "the value of node " << i << ":" << pNode->value << endl;
		nodes.pop();
		i++;
	}
}

//printf the node from the tail using recursion
void PrintFromTailRecursion(ListNode* pHead)
{
	//ListNode* pNode = *pHead;
	int i = 0;
	if (pHead != NULL)
	{
		if (pHead->pNext != NULL)
		{
			PrintFromTailRecursion(pHead->pNext);
		}
		cout << "the value of node " << i << ":" << pHead->value << endl;
		i++;
	}
}
//main function 
int main()
{
	struct ListNode* pHead = NULL;
	for (int i = 0; i < 10; i++)
	{
		AddToTail(&pHead, i);
	}
	cout << "---Print from the head--- " << endl;
	PrintFromHead(&pHead);
	cout << "---After removing digit 5---" << endl;
	RemoveNode(&pHead, 5);
	PrintFromHead(&pHead);
	cout << "---Print from the tail--- " << endl;
	PrintFromTail(&pHead);
	cout << "---Print using recursion--- " << endl;
	PrintFromTailRecursion(pHead);
	system("PAUSE");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值