C++封装链表 类
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C++封装链表 类,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1715字,纯文字阅读大概需要3分钟。
内容图文
![C++封装链表 类](/upload/InfoBanner/zyjiaocheng/737/ce5e6e3ced3246448c61e28cb0118b92.jpg)
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();
}
内容总结
以上是互联网集市为您收集整理的C++封装链表 类全部内容,希望文章能够帮你解决C++封装链表 类所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。