#C++ Day52 Basic Data Structure Chapter6  Linked List-Actual questions Coding  January 14 2026

    #include<iostream>

#include<stdexcept>

using namespace std;

#define eleType int

//1.链表结点结构体

struct ListNode {

eleType data;//存储结点的数据域

ListNode* next;//指向链表的下一个结点

ListNode(eleType x):data(x),next(nullptr){}//ListNode结构体的构造函数

};

//2.初始化单链表

class LinkedList {

private:

ListNode* head;

int size;

public:

LinkedList() :head(NULL), size(0){}//构造函数 初始化一个空链表 

~LinkedList();

void insert(int index,eleType value);

void remove(int index);

ListNode* find(eleType value);

ListNode* get(int index);

void update(int index, eleType value);

void print();

};

//3.单向链表的销毁 实现析构函数

LinkedList::~LinkedList() {

ListNode* curr = head;

while (curr != NULL) {

ListNode* temp = curr;

curr = curr->next;

delete temp;

}

}

//4.单向链表的元素插入

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 = newNode;

}

else {

ListNode* curr = head;

for (int j = 0; j < i – 1; j++) {

curr = curr->next;

}

newNode->next=curr->next;

curr->next = newNode;

}

size++;

}

//5.单向链表的元素删除

void LinkedList::remove(int i) {

if (i < 0 || i >= size) {

throw std::out_of_range(“Invalid Position”);

}

if (i == 0) {

ListNode* temp = head;

head = temp->next;

delete temp;

}

else {

ListNode* curr = head;

for (int j = 0; j < i – 1; j++) {

curr = curr->next;

}

ListNode* temp = curr->next;

curr->next = temp->next;

delete temp;

}

size–;

}

//6.单向链表的元素查找

ListNode* LinkedList::find(eleType value) {

ListNode* curr = head;

if (curr != NULL && curr->data != value) {

curr = curr->next;

}

return curr;

}

//7.单向链表的元素索引

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++) {

curr = curr->next;

}

return curr;

}

//8.单向链表的元素修改

void LinkedList::update(int i,eleType value){

if (i < 0 || i >= size) {

std::out_of_range(“Invalid position”);

}

get(i)->data = value;

}

//9.单向链表的打印

void LinkedList::print() {

ListNode* curr = head;

while (curr != NULL) {

cout << curr->data << ” “;

curr = curr->next;

}

std::cout << endl;

}

int main() {

LinkedList mylist;

mylist.insert(0, 10);

mylist.insert(1, 20);

mylist.insert(2, 30);

mylist.insert(3, 40);

std::cout << “Initial list:”;

mylist.print();

cout << “Removing the third node:” ;

mylist.remove(2);

mylist.print();

cout << “Updating the second node to 666:”;

mylist.update(1, 666);

mylist.print();

cout << “Finding the value of the \”666\” node:”;

cout<<mylist.find(666)->data<<endl;

cout << “Getting the first node:”;

cout << mylist.get(0)->data << endl;

return 0;

}