C++链表
今天的种树是练习一下C++的数据结构的使用。链表没啥好介绍的直接上代码。
c++实现
主要内容写了三个函数:1.利用堆栈倒序打印链表 2.把一个节点添加到链表末尾 3.删除第一个值为value的节点
#include <iostream>
#include <stack>
using namespace std;
struct List
{
int value;
List* next;
};
//利用堆栈倒叙打印链表
void printListNode(List* head)
{
std::stack<List*> nodes;
List* node = head;
while(node != nullptr)
{
nodes.push(node);
node = node->next;
}
while(!nodes.empty())
{
node = nodes.top();
printf("%d ", node->value);
nodes.pop();
}
}
//把一个节点添加到链表末尾
void AddToTail(List** head, int value)
{
List* newNode = new List();
newNode->value = value;
newNode->next = nullptr;
if(*head == nullptr)
{
*head = newNode;
}
else
{
List* node = *head;
while(node->next != nullptr)
node = node->next;
node->next = newNode;
}
}
//删除第一个值为value的节点
void DeleteTailNode(List** head, int value)
{
if(*head == nullptr)
return;
List* ToBeDeleted = nullptr;
if((*head)->value == value)
{
ToBeDeleted = *head;
*head = (*head)->next;
}
else
{
List* pNode = *head;
while(pNode->next != nullptr && pNode->next->value != value)
pNode = pNode->next;
if(pNode->next->value == value && pNode->next->next != nullptr)
{
ToBeDeleted = pNode->next;
pNode->next = pNode->next->next;
}
}
if(ToBeDeleted != nullptr)
{
delete ToBeDeleted;
ToBeDeleted = nullptr;
}
}
int main()
{
List* head = new List();
head->value = 1000;
head->next = nullptr;
for(int i = 1; i <= 10; i++)
AddToTail(&head, i);
printListNode(head);
cout << endl;
DeleteTailNode(&head, 5);
printListNode(head);
}
运行结果
写论文真的烦,种树+2