C++链表实例(未完成的)

#include <iostream>

using namespace std;
class Node
{
public:
	int data;
	Node * next = nullptr;
	Node() = default;
	Node(int value) { data = value; }
};

class List
{
public:
	Node * head = nullptr;
	List() = default;
	~List();
	int getLength();
	bool insert(Node * node, int pos);
	bool remove(int pos);
private:
	int length = 0;
};
List::~List()
{
	Node * temp = head;
	while (temp)
	{
		Node * temp2 = temp;
		temp = temp->next;
		delete temp2;
	}
}

int List::getLength()
{
	return length;
}

bool List::insert(Node * node, int pos)
{
	//只能从位置 1 和 length +1 之间插入
	if (pos<1 || pos > length + 1)
	{
		cout << "invalid pos to insert" << endl;
	}
	if (pos == 1)
	{
		if (head == nullptr)
		{
			head = node;
		}
		else
		{
			node->next = head;
			head = node;
		}
		cout << "insert from head success" << endl;
	}
	else
	{
		Node * pre_node = head;
		int i = 1;
		//捕获要插入节点的前一个节点
		while (i <pos-1)
		{
			i++;
			pre_node = pre_node->next;
		}
		//衔接链表
		node->next = pre_node->next;
		pre_node->next = node;
		cout << "insert from no-head success" << endl;
	}
	++length;
	return true;
}

bool List::remove(int pos)
{
	//只能删除 1 ... length 位置
	if (pos <1 || pos >length)
	{
		cout << "invalid pos to remove" << endl;
		return false;
	}

	if (pos ==1)
	{
		Node * temp = head;
		head = head->next;
		delete temp;
		cout << "delete head success" << endl;
	}
	else
	{
		Node * temp = head;
		int i = 1;
		//捕获要删除的节点的前一个节点
		while (i < pos - 1)
		{
			++i;
			temp = temp->next;
		}
		Node * del_node = temp->next;
		temp->next = del_node->next;
		delete del_node;
		cout << "delete from other no-head pos success,pos = " << pos << endl;
	}
	--length;
	return true;
}

void printList(List& list)
{
	const int len = list.getLength();
	Node * temp = list.head;
	int i = 0;
	while (temp)
	{

		cout << ++i << " : " << temp->data << endl;
		temp = temp->next;
	}

}

int main(void)
{
	Node * n1 = new Node(1);
	Node * n2 = new Node(2);
	Node * n3 = new Node(3);
	Node * n4 = new Node(4);
	List mylist = List();

	mylist.insert(n1, 1);
	mylist.insert(n2, 2);
	mylist.insert(n3, 3);
	mylist.insert(n4, 1);
	printList(mylist);
	mylist.remove(4);
	printList(mylist);
	mylist.remove(2);
	printList(mylist);
	mylist.remove(1);
	printList(mylist);
	mylist.remove(1);
	printList(mylist);
}


原文地址:https://www.cnblogs.com/Fallever/p/6880640.html