#include <iostream>
#include <stdlib.h>
using namespace std;
struct node{
int data;
node* next=NULL;
//结构体内带函数是C++语法 C语言中不能这样用
node(){
}
node(int x,node* p=NULL){
data = x;
next = p;
}
};
class List{
private:
node* head;
public:
List(){
head = NULL;
}
bool insert(int i, int& n);
bool remove(int i);
bool search(const int i);
bool change(int i, int& n);
void display()
{
node* p = head;
while (p)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
};
bool List::insert(int i, int& n)
{
if (head == NULL || i == 0)
{
node* newnode = new node();
if (newnode == NULL)
{
cerr << "Memoey Error" << endl;
exit(1);
}
newnode->data = n;
newnode->next = head;
head = newnode;
}
else
{
node* current = head;
//找到第i个节点
for (int j = 1; j < i; j++)
{
if (current == NULL) break;
else
current = current->next;
}
if (current == NULL && head != NULL)
{
cerr << "Too short" << endl;
return false;
}
else
{
node* newnode = new node();
if (newnode == NULL)
{
cerr << "Memoey Error" << endl;
exit(1);
}
newnode->data = n;
newnode->next = current->next;
current->next = newnode;
}
}
return true;
}
bool List::remove(int i)
{
if (head == NULL || i < 0)
{
cerr << "Error" << endl;
exit(1);
}
if (i <= 1)
{
node* del = head;
head = head->next;
delete del;
}
else
{
node* current = head;
//找到第i-1个节点
for (int j = 1; j < i - 1; j++)
{
if (current == NULL)
{
cerr << "Too short" << endl;
return false;
}
else
current = current->next;
}
node* del = current->next;
current->next = del->next;
delete del;
}
return true;
}
int main()
{
List l;
for (int i = 1; i <= 20; i++)
{
l.insert(0, i);
}
l.display();
l.remove(2);
l.display();
l.remove(0);
l.display();
//l.remove(20);Error
getchar();
}
链表增删节点
最新推荐文章于 2022-07-31 22:43:17 发布