qfedu-cpp-level/day3/homework/h5.cpp

149 lines
2.5 KiB
C++

// 创建一个名为 LinkedList 的类,实现链表的基本操作,包括插入节点、删除节点和反转链表等。
// 【提示】单向链表
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
class Node
{
public:
int data;
Node *next;
public:
Node(int value)
{
this->data = value;
this->next = NULL;
}
};
class LinkedList
{
private:
Node *head;
public:
LinkedList()
{
head = NULL; // 初始头结点
}
public:
Node *insertNode(int insValue);
Node *deleteNode(int delValue);
Node *reverseLinkedList();
void print();
};
Node *LinkedList::insertNode(int insValue)
{
Node *newNode = new Node(insValue);
if (NULL == head)
head = newNode;
Node *p = head;
while (p->next != NULL)
{
p = p->next;
}
p->next = newNode;
return head;
}
Node *LinkedList::deleteNode(int delValue)
{
if (NULL == head)
{
cout << "不存在链表,删除失败" << endl;
return head;
}
if (head->data == delValue) // 当删除的节点是头节点时
{
Node *temp = head;
head = head->next;
delete temp;
return head;
}
Node *p = head;
while (p->next != NULL)
{
if (p->next->data == delValue)
{
Node *temp = p->next;
p->next = temp->next;
delete temp;
}
p = p->next;
}
if (p != NULL && p->data == delValue) // 处理最后一个节点的情况
{
delete p;
p = NULL;
}
return head;
}
Node *LinkedList::reverseLinkedList()
{
Node *p = head;
Node *new_head = NULL;
Node *p_next = NULL;
while (p != NULL)
{
p_next = p->next;
p->next = new_head;
new_head = p;
p = p_next;
}
head = new_head; // 新头指针
return head;
}
void LinkedList::print()
{
Node *p = head;
while (p != NULL)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
int main()
{
LinkedList list;
// 插入节点
list.insertNode(1);
list.insertNode(3);
list.insertNode(8);
list.insertNode(2);
// 测试打印
cout << "原始链表: ";
list.print();
cout << endl;
// 删除节点
list.deleteNode(3);
cout << "删除3后的链表: ";
list.print();
cout << endl;
// 反转链表
list.reverseLinkedList();
cout << "反序链表后: ";
list.print();
cout << endl;
return 0;
}