List.h
#ifndef LIST_H
#define LIST_H
#include<stdio.h>
#include<iostream>
#define TYPE int
using namespace std;
class Node
{
public:
TYPE data;
Node* next;
Node(TYPE _data)
{
data = _data;
next = NULL;
}
};
class List
{
public:
Node* head;
Node* tail;
size_t _size;
List(void)
{
head = NULL;
tail = NULL;
_size = 0;
}
~List(void);
//头添加
void head_add(TYPE data);
//
void tail_add(TYPE data);
//
bool head_del(void);
//
bool tail_del(void);
size_t size(void);
void show(void);
};
#endif//LIST_H
List.cpp
#include "list.h"
List::~List(void)
{
cout << "我是List的析构函数" << endl;
}
//头添加
void List::head_add(TYPE data)
{
Node* node = new Node(data);
if(0 == _size)
{
head = node;
tail = node;
}
else
{
node->next = head;
head = node;
}
_size++;
}
//尾添加
void List::tail_add(TYPE data)
{
Node* node = new Node(data);
if(0 == _size)
{
head = node;
tail = node;
}
else
{
tail->next = node;
tail = node;
}
_size++;
}
//头删除
bool List::head_del(void)
{
if(0>=_size) return false;
Node*temp = head;
head = temp->next;
if(1 == _size)
{
tail = NULL;
}
delete temp;
_size--;
return true;
}
//尾删除
bool List::tail_del(void)
{
Node* _tail = tail;
if( 0 >= _size) return false;
if(1 == _size)
{
head_del();
return true;
}
else
{
Node* prev=head;
while(prev->next!=_tail)
{
prev = prev->next;
}
tail = prev;
prev->next = NULL;
delete _tail;
}
_size--;
return true;
}
//长度
size_t List::size(void)
{
size_t size;
size = _size;
cout << "链表的长度是:"<< size << endl;
}
//遍历
void List::show(void)
{
Node* node =head;
for(head;head!=NULL;head = head->next)
{
cout << head->data << endl;
}
}
main.pp
#include <iostream>
#include "list.h"
using namespace std;
int main()
{
List list;
list.head_add(1);
list.head_add(2);
list.head_add(3);
list.tail_add(4);
//list.head_del();
list.tail_del();
list.size();
list.show();
}