手写实现单向链表 [ C++ ]

#include 
using namespace std;

template
class Node {
public:
	Type date_;
	Node* next_;
	Node(const Type& date) :date_(date), next_(nullptr) {};
};


template
class LinkedList {
private:
	Node* head;
public:
	LinkedList() {
		head = nullptr;
	}

	~LinkedList() {
		Node* currnet_node = head;
		while (currnet_node != nullptr) {
			Node* delete_node = currnet_node;
			currnet_node = currnet_node->next_;
			delete delete_node;
		}
	}

	void insert(Node* node, int index);
	void output();
	//void deleteNode(int index);
	//void reverse();

};



template
void LinkedList::insert(Node* node, int index) {
	// 1
	if (head == nullptr) {
		if (index != 0) {
			return;
		}
		head = node;
		return;
	}
	// 2
	if (index == 0) {
		node->next_ = head;
		head = node;
	}
	// 一般的插入操作
	Node* current_node = head;
	int count = 0;
	while (current_node->next_ != nullptr && (count < index - 1)) {
		current_node = current_node->next_;
		count++;
	}

	if (count == index - 1) {
		node->next_ = current_node->next_;
		current_node->next_ = node;
		return;
	}
	return;
}

template
void LinkedList::output() {
	if (head == nullptr) return;

	Node* current_node = head;
	while (current_node != nullptr) {
		cout << current_node->date_ << " ";
		current_node = current_node->next_;
	}
	cout << endl;
}


int main() {
	LinkedList linkedlist;
	for (int i = 1; i <= 10; ++i) {
		Node* node = new Node(i);
		linkedlist.insert(node, i - 1);
	}
	linkedlist.output();

	system("PAUSE");
	return 0;
}

你可能感兴趣的:(C++学习,c++,stl)