本文使用C++实现了一个线性表(数组描述)。该程序由三个文件构成,第一部分是头文件,头文件定义了一个链表的节点的结构体,同时在该结构体的基础上定义了一个线性表类,该抽象类中定义了绝大部分线性表的成员函数,其中包括:
- 确定线性表是否为空
- 确定线性表中数据的数目
- 添加一个数据
- 按一个给定索引查找其对应的元素
- 按数据删除一个节点
- 遍历输出(反向输出)该线性表
- 格式化该线性表
- 排序(反向排序)该线性表
第二部分是测试代码。整个程序使用Xcode编译。其中,头文件源码如下:
//
// Node_List.hpp
// node_list
//
// Created by lq on 2019/9/2.
// Copyright © 2019 Mr.liang. All rights reserved.
//
#ifndef Node_List_hpp
#define Node_List_hpp
#include <iostream>
using namespace std;
struct node
{
node* next;
node* last;
int data;
};
class node_chain
{
private:
node* head;
node* tail;
int length;
public:
node_chain()
{
head = new node;
tail = new node;
head->next = tail;
head->last = nullptr;
tail->next = nullptr;
tail->last = head;
length = 0;
}
node_chain(const node_chain &s)
{
head = new node;
tail = new node;
head->next = tail;
head->last = nullptr;
tail->last = head;
length = 0;
node* temp = s.head;
while(temp->next != s.tail)
{
temp =