#include<iostream>
#include<stdexcept>
using namespace std;
#define eleType int
struct ListNode
{
eleType m_data;
ListNode* next;
ListNode(eleType data)
{
m_data = data;
next = NULL;
}
};
class Linkedlist
{
private:
ListNode* head;
int size;
public:
Linkedlist()
{
head = NULL;
size = 0;
}
~Linkedlist();
void insert(int i, eleType a);
void remove(int i);
ListNode* find(eleType a);
ListNode* get(int i);
void update(int i, eleType a);
void print();
};
Linkedlist::~Linkedlist()
{
ListNode* curr = head;
if (curr != NULL)
{
ListNode* temp = curr;
curr = curr->next;
delete temp;
}
}
void Linkedlist::insert(int i, eleType a)
{
if (i<0 || i>size)
{
throw std::out_of_range("下标不对");
}
else
{
ListNode* newNode = new ListNode(a);
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++;
}
}
void Linkedlist::remove(int i)
{
if (i<0 || i>=size)
{
throw std::out_of_range("下标不对");
}
else
{
if (i == 0)
{
ListNode* temp = head;
head = head->next;
delete temp;
}
ListNode* curr = head;
for (int j = 0; j < i - 1; j++)
{
curr = curr->next;
}
ListNode* temp2 = curr->next;
curr->next = temp2->next;
delete temp2;
size--;
}
}
ListNode* Linkedlist::find(eleType a)
{
ListNode* curr = head;
while (curr && curr->m_data != a)
{
curr = curr->next;
}
if (curr->m_data != a)
{
cout << "没有该元素" << endl;
return NULL;
}
if (curr)
{
return curr;
}
}
ListNode* Linkedlist::get(int i)
{
if (i < 0 || i >= size)
{
throw std::out_of_range("下标不对");
}
ListNode* curr = head;
for (int j = 0; j < i; j++)
{
curr = curr->next;
}
return curr;
}
void Linkedlist::update(int i, eleType a)
{
if (i < 0 || i >= size)
{
throw std::out_of_range("下标不对");
}
ListNode* curr = head;
for (int j = 0; j < i; j++)
{
curr = curr->next;
}
curr->m_data = a;
}
void Linkedlist::print()
{
ListNode* curr = head;
while (curr)
{
cout << curr->m_data << " ";
curr = curr->next;
}
cout << endl;
}
int main()
{
Linkedlist list;
list.insert(0, 10);
list.insert(1, 20);
list.print();
return 0;
}
标签:head,ListNode,Linkedlist,int,C++,next,链表,curr
From: https://blog.csdn.net/2401_83496535/article/details/142964210