#include<iostream>
using namespace std;
class Node {
public:
int val;
Node* next;
Node() :val(0), next(nullptr) {}
Node(int x) :val(x), next(nullptr) {}
void PrintNode();
};
void Node::PrintNode() {
cout <<val<<endl;
}
class ListNode {
private:
Node* head;
public:
ListNode();
void AddNodePre(Node* node);
void AddNodePost(Node* node);
void CreateList(int n);
void PrintList();
void DeleteNode(int x);
int GetSize();
void ModifyNode(int pos, int val);
~ListNode();
};
ListNode::ListNode() {
head = new Node();
}
void ListNode::AddNodePre(Node *node) {
Node* temp = new Node(*node);
//头插法
temp->next = head->next;
head->next = temp;
}
void ListNode::AddNodePost(Node* node) {
Node* temp = new Node(*node);
Node* t = head;
while (t->next) {
t = t->next;
}
t->next = temp;
}
void ListNode::PrintList() {
Node* temp = head->next;
while (temp) {
temp->PrintNode();
temp = temp->next;
}
}
void ListNode::CreateList(int n) {
Node* t = head;
for (int i = 0; i < n; i++) {
Node* temp = new Node(i);
t->next = temp;
t = t->next;
}
return;
}
void ListNode::DeleteNode(int x) {
//x表示第几个节点 head不算
int i = 1;
Node* node = head->next;
Node* t = head;
while (node) {
if (i == x) {
t->next = node->next;
delete node;
break;
}
t = t->next;
node = node->next;
i++;
}
}
int ListNode::GetSize() {
Node* temp = head->next;
int i = 0;
while (temp) {
i++;
temp = temp->next;
}
return i;
}
void ListNode::ModifyNode(int pos, int val) {
Node* temp = head->next;
int i = 0;
while (temp) {
i++;
if (i == pos) {
temp->val = val;
break;
}
temp = temp->next;
}
}
ListNode::~ListNode() {
Node* temp = head;
Node* t;
while (temp) {
t = temp->next;
delete temp;
temp = t;
}
}
int main() {
ListNode test;
cout << "初始:" << endl;
Node node1(25);
Node node2(26);
Node node3(27);
Node node4(28);
test.AddNodePre(&node1);
test.AddNodePre(&node2);
test.AddNodePost(&node3);
test.AddNodePost(&node4);
test.PrintList();
ListNode test1;
test1.CreateList(10);
cout << "初始" << endl;
test1.PrintList();
int len=test1.GetSize();
cout << "长度:" << len << endl;
cout << "删除第三个" << endl;
test1.DeleteNode(3);
test1.PrintList();
cout << "第五个位置上改成100" << endl;
test1.ModifyNode(5, 100);
test1.PrintList();
}
链表(类封装)C++
最新推荐文章于 2024-07-23 22:06:37 发布