单链表相关的基本操作(从文件中读入)

单链表相关的基本操作

  1. 初始化单链表
  2. 头插法建表
  3. 尾插法建表
  4. 插入元素
  5. 删除元素
  6. 判空表
  7. 单链表倒置

头文件:

#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) //删除元素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
发布了16 篇原创文章 · 获赞 25 · 访问量 1141

猜你喜欢

转载自blog.csdn.net/weixin_41546300/article/details/104649539