您的位置:首页 > 理论基础 > 数据结构算法

数据结构——线性表——链式存储结构——C++实现线性表

2017-05-13 10:01 441 查看
链式存储结构C++实现篇:主要实现了线性表的定义、初始化、显示、增、删结点、查找结点操作。

切记亲力亲为,动手实践写代码

main.cpp

/***************************************************************************
*  @file       main.cpp
*  @author     MISAYAONE
*  @date       11  May 2017
*  @remark     11  May 2017
*  @theme      Linked List
***************************************************************************/
#include "Linked_list.h"

#include <iostream>
using namespace std;

int main(int argc, char** argv)
{
Linked_list L;
Init_linkedlist_back(L);

cout<<"链表包含元素为:";
Display(L);
cout<<endl;

//查找结点值为2的结点
node *p = Getelem(L,4);

add(L,p,2);

cout<<"插入新结点之后包含元素为";
Display(L);

cout<<endl;
node *q = Getelem(L,3);
Delete(L,q);
cout<<"删除结点之后包含元素为";
Display(L);

system("pause");
return 0;
}


Linked_list.h

#include "Linked_list.h"

#include <iostream>
using std::cin;
using std::cout;
using std::endl;

//注意链表的表示方法:通常使用第一个结点来标识一个链表,头插法
bool Init_linkedlist(Linked_list &L)
{
node *node1; //新建一结点
int x;       //用于存放输入的结点值
L = (Linked_list)malloc(sizeof(node));
L->next = NULL;
while(cin>>x)
{
node1 = (node*)malloc(sizeof(node));  //先分配内存,以便后面的使用

node1->data = x;      //将值存入当前结点

node1->next = L->next; //将当前结点置于表头
L->next = node1;
}
return true;
}

//注意链表的表示方法:通常使用第一个结点来标识一个链表,尾插法
bool Init_linkedlist_back(Linked_list &L)
{
node *node1,*node2; //新建结点
int x;       //用于存放输入的结点值
L = (Linked_list)malloc(sizeof(node));
L->next = NULL;
node2 = L;
while(cin>>x)
{
node1 = (node*)malloc(sizeof(node));  //先分配内存,以便后面的使用

node1->data = x;      //将值存入当前结点

node2->next = node1; //将当前结点置于表尾
node2 = node1;
node1->next = NULL;
}
node2->next = NULL;
return true;
}

bool Display(Linked_list L)
{
node *p = L;
while (p && p->next)     //P结点以及P的后继结点都不为NULL
{
p = p->next;
cout<<p->data<<" ";

}
return true;
}

//按值查找
node *Getelem(Linked_list L,datatype i)
{
node *p = L;
while(p->data != i && p != NULL)
{
if (p->next == NULL)  //若未找到,返回NULL
{
return NULL;
}
p = p->next;
}
return p;
}

//在结点p之后插入值为i的新结点
bool add(Linked_list &L,node *p,int i)
{
if (p == NULL)       //判断传入结点的有效性
{
return true;
}
node *p1;
p1 = (node*)malloc(sizeof(node));
p1->data = i;
p1->next = p->next;
p->next = p1;
return true;
}

//删除结点p,需要先找到p的前驱结点
bool Delete(Linked_list &L, node *p)
{
if (p == NULL)       //判断传入结点的有效性
{
return true;
}
node *q = L;
while (q->next != p)
{
q = q->next;
}
q->next = p->next;
free(p);//注意需要释放p结点
return true;
}


Linked_list.cpp

typedef int datatype;//将链表中的数据元素定义为int

typedef struct node
{
datatype data;
struct node* next;
} *Linked_list;        //定义结构别名

//链表初始化
bool Init_linkedlist(Linked_list &L);

//尾插法
bool Init_linkedlist_back(Linked_list &L);

//按值查找结点
node *Getelem(Linked_list L,datatype i);

//链表插入结点
bool add(Linked_list &L,node *p,int i);

//链表删除结点
bool Delete(Linked_list &L, node *p);

//显示链表全部结点
bool Display(Linked_list L);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息