代码: // Test_Console_3.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include iostream #includecstdlib using namespace std ; // 链表结构体 typedef struct listpoint { int data ; // 数据 listp
代码:
// Test_Console_3.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。//
#include <iostream>
#include<cstdlib>
using namespace std;
// 链表结构体
typedef struct listpoint
{
int data; // 数据
listpoint* next; // 指向下一节点的指针
}listpoint;
// 插入数据
listpoint* insertNode(listpoint* head, int data) {
listpoint* newNode = new listpoint();
newNode->data = data;
listpoint* p = head;
if (p == nullptr) {
head = newNode;
}
else {
while (p->next != nullptr) {
p = p->next;
}
p->next = newNode;
}
return head;
}
// 删除数据
listpoint* deleteNode(listpoint* head, int data) {
listpoint* p = head;
if (p == nullptr) {
return head;
}
if (p->data == data) {
head = p->next;
delete p;
return head;
}
while (p->next != nullptr && p->next->data != data) {
p = p->next;
}
if (p->next == nullptr) {
return head;
}
listpoint* deleteNode = p->next;
p->next = deleteNode->next;
delete deleteNode;
return head;
}
int main()
{
// 创建链表
listpoint* head = new listpoint();
head->data = 0; head->next = nullptr;
listpoint* lp = head;
// 插入数据
insertNode(head, 1);
insertNode(head, 2);
insertNode(head, 3);
// 打印链表
lp = head;
while (lp) {
cout << lp->data << endl;
lp = lp->next;
}
// 删除数据
deleteNode(head, 3);
// 打印链表
lp = head;
while (lp) {
cout << lp->data << endl;
lp = lp->next;
}
getchar();
return 0;
}
效果图: