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