单链表相关的基本操作
- 初始化单链表
- 头插法建表
- 尾插法建表
- 插入元素
- 删除元素
- 判空表
- 单链表倒置
头文件:
#ifndef _LINKLIST_H_
#define _LINKLIST_H_
#include <iostream>
#include <fstream>
using namespace std;
#define OK 1
#define ERROR 0
typedef int Status;
typedef int ELEMTYPE;
typedef struct LNode
{
ELEMTYPE data;
struct LNode *next;
}LNode,*LinkList;
Status initLinkList(LinkList &L)
{
L = new LNode;
if (!L)
{
cout << "空间不足" << endl;
return ERROR;
}
L->next = NULL;
}
Status CreateLinkList_head(LinkList &L)
{
fstream file;
file.open("data.txt",ios::in);
if(!file)
{
cout << "打开文件失败\n";
return ERROR;
}
while (!file.eof())
{
LNode *p = new LNode;
file >> p->data;
p->next = L->next;
L->next = p;
}
}
Status CreateLinkList_rear(LinkList &L)
{
fstream file;
file.open("data.txt",ios::in);
if(!file)
{
cout << "打开文件失败\n";
return ERROR;
}
LNode *rear = L;
while (!file.eof())
{
LNode *p = new LNode;
file >> p->data;
p->next = NULL;
rear->next = p;
rear = p;
}
}
bool isEmpty(LinkList L)
{
if (L->next == NULL)
return true;
return false;
}
void Visit(LinkList L)
{
LNode *p = L->next;
while (p)
{ cout<< p->data <<" ";
p = p->next;
}
cout << endl;
}
Status InsertData(LinkList &L,ELEMTYPE e,int n)
{
int i = 0;
LNode *p = L;
while (p)
{
if (i == n - 1)
{
LNode *q = new LNode;
q->data = e;
q->next = p->next;
p->next = q;
return OK;
}
p = p->next; i++;
}
cout<<"插入位置不合法\n";
return ERROR;
}
Status deleteData(LinkList &L,ELEMTYPE e)
{
LNode *p = L,*q;
while (p->next)
{
if (p->next->data == e)
{
q = p->next;
p->next = q->next;
delete (q);
return OK;
}
p = p->next;
}
cout<<"没有该元素"<<endl;
return ERROR;
}
Status deletePo(LinkList &L,int n)
{
if (isEmpty(L))
{
cout<<"空表\n";
return ERROR;
}
int i = 0;
LNode *p = L,*q;
while (p->next)
{
if (i == n - 1)
{
q = p->next;
p->next = q->next;
delete (q);
return OK;
}
p = p->next;i++;
}
cout<<"删除位置不合法"<<endl;
return ERROR;
}
void Reverse(LinkList &L)
{
LNode *p = L->next,*q;
L->next = NULL;
while (p)
{
q = p->next;
p->next = L->next;
L->next = p;
p = q;
}
}
#endif