#include <iostream>
using namespace std;
#define eleType int
#include <stdexcept>
struct ListNode {
eleType data;
ListNode* next;
ListNode(eleType x) : data(x) ,next(NULL){}//初始化列表
};
class LinkedList {
private:
ListNode* head;
int size;
public:
LinkedList() :head(NULL) , size(0){}//构造函数进行初始化
~LinkedList();
void insert(int i, eleType value);
void remove(int i);
ListNode* find(eleType value);
ListNode* get(int i);
void update(int i, eleType value);
void print();
};
LinkedList::~LinkedList() {//析构函数
ListNode *curr = head;
while (curr != NULL) {//释放节点内存内存
ListNode* tmp = curr;
curr = curr->next;
delete tmp;
}
}
//插入
void LinkedList::insert(int i, eleType value) {
if (i < 0 || i > size) {
throw std::out_of_range("Invalid position");
}
ListNode* newNode = new ListNode(value);
if (i == 0) {
newNode->next = head;//如果要插入头结点,先将新节点的指针指向旧的头节点,再将新节点赋值给head
head = newNode;
}
else {
ListNode* curr = head;
for (int j = 0; j < i - 1; j++) {//遍历完成后curr位于要插入节点的前一个结点
curr = curr->next;
}
newNode->next = curr->next;//这一步很关键,将我们要插入节点的前一个结点的指针赋值给新节点(即我们要拿来插入的节点)的指针
curr->next = newNode; //再将curr的指针指向新节点,此时新节点在curr节点和原来curr节点后一节点中间
}//结合图像
++size;
}
//删除
void LinkedList::remove(int i) {
if (i < 0 || i >= size) {
throw std::out_of_range("Invalid position");
}
if (i == 0) {
ListNode* temp = head;//删除头节点,先将它存下来,然后将它下一个节点当作头节点,最后删除
head = head->next;
delete temp;
}
else {
ListNode* curr = head;
for (int j = 0; j < i - 1; j++) {//类似于插入,让curr往后走到要删除节点的前一个结点
curr = curr->next;
}
ListNode* temp = curr->next;//将要删除的节点存下来,再将该节点的后继节点当作curr的后继节点
curr->next = temp->next;
delete temp;
}
--size;
}
//查找值
ListNode* LinkedList::find(eleType value) {
ListNode* curr = head;
while (curr && curr->data != value) {//当节点不为空且节点内的数据不符,则curr往后移,直到找到
curr = curr->next;//如果找到了是正常返回,如果最后遍历完curr最后变为NULL,即没找到
}
return curr;
}
//索引
ListNode* LinkedList::get(int i) {
if (i < 0 || i >= size) {
throw std::out_of_range("Invalid position");
}
ListNode* curr = head;
for (int j = 0; j < i ; j++) {//此处为i 不是 i-1
curr = curr->next;
}
return curr;
}
//更改
void LinkedList::update(int i, eleType value) {
get(i)->data = value;//直接调用上面的get拿到data,再将新的值赋值给它即可
}
void LinkedList::print() {
ListNode * curr = head;
while (curr) {
cout << curr->data << " ";
curr = curr->next;
}
cout << endl;
}
int main() {
LinkedList list;
list.insert(0, 10);
list.insert(1, 20);
list.insert(2, 30);
list.insert(3, 40);
list.insert(4, 50);
list.print();
list.remove(1);
list.print();
list.update(2, 60);
list.print();
ListNode *tmp =list.find(30);
cout << tmp->data << endl;
cout << list.get(3)->data << endl;
system("pause");
return 0;
}