链表增删节点

#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();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值