Structure:List

\\--------------------------- List.h-----------------------
#pragma once
// 鏈表結點
class Node {
public:
	Node() { next = nullptr; }
	Node(int data, Node * node = nullptr) {
		this->data = data;
		this->next = node;
	}
	int data;
	Node *next;
};

class List {
public:
	List() { head = nullptr; tail = nullptr; }
	~List();
	
	int isEmpty() { return head == 0;}
	
	void addToHead(int);
	void addToTail(int);
	int deleteFromHead();
	int deleteFromTail();
	void deleteNode(int);
	bool isInList(int);
	void show();

private:
	Node *head, *tail;
};
\\--------------------------- List.cpp-----------------------
#include "List.h"
#include <iostream>

List::~List() {
	for (Node *p; !isEmpty();) //從頭節點開始刪除,直到頭結點爲空
	{
		p = head->next;
		delete head;
		head = p;
	}
}

// 從頭增加結點
void List::addToHead(int a) {
	head = new Node(a, head);           // 新建結點並將其next設爲head
	if (tail == nullptr) {tail = head;} // 如果鏈表爲空,插入結點後需要設置尾結點
}
// 從尾加結點
void List::addToTail(int a) {
	if (tail != nullptr) //如果鏈表不爲空
	{
		tail->next = new Node(a);
		tail = tail->next;
	}
	else head = tail = new Node(a);
}

// 從頭刪結點
int List::deleteFromHead() {

	// 如果鏈表爲空,無法刪除,拋出異常,由用戶用try{n = deleteFromHead();}catch{char *s}{cerr<<"Error:"<<s<<endl;}捕獲
	if (isEmpty()) { throw("empty"); } 

	int num = head->data;
	Node *p = head;
	if (head == tail){
		head = tail = nullptr;
	}
	else{
		head = head->next;
	}
	delete p;
	return num;
}

// 從尾刪除結點
int List::deleteFromTail() {
	int num = tail->data;
	if (head == tail){
		head = tail = nullptr;
	}
	else
	{
		Node *p;
		for ( p = head; p->next != tail; p = p->next);  
		delete tail;
		tail = p;
		tail->next = nullptr;
	}
	return num;
}

// 刪除一個包含特定整數的結點
void List::deleteNode(int a) {
	if (head != nullptr)
	{
		if (head == tail && a == head->data) // 一個結點是查找的點
		{
			head = tail = nullptr;
		}
		else if( a == head->data)   //多個結點,查找的點在頭
		{
			Node *p = head;
			head = head->next;
			delete p;
		}
		else // 多個結點,查找的點不在頭
		{
			Node *p= head->next;
			Node *pre = head;
			for (; p!=nullptr && p->data != a; p = p->next,pre = pre->next);
			if (p != nullptr)
			{
				pre->next = p->next;
				if (tail == p) tail = pre;
				delete p;
			}
		}
	}
}

bool List::isInList(int a) {
	Node *p = nullptr;
	for (p = head; p->data != a; p = p->next);
	return p != nullptr; // 結點存在鏈表中則返回1,否則返回0
}

void List::show() {
	for (Node *p = head;p!=nullptr;p = p->next)
	{
		std::cout << p->data << std::endl;
	}
}
int main(int argc, char ** argv)
{
	List * list = new List();
	list->addToHead(20);
	list->addToHead(10);
	list->addToTail(30);
	list->show();
	
	list->deleteFromHead();
	list->show();

	list->deleteFromTail();
	list->show();

	list->deleteNode(10);
	list->show();

	list->addToHead(10);
	list->show();
	list->deleteNode(10);
	list->show();

	cout << list->isInList(20) << endl;

	system("pause");
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章