严版数据结构第28页定义的单链表存储结构:
typedef struct LNode {
ElemType data;
struct LNode *next;
}LNode,*LinkedList;
实现书中算法2.8——2.11:
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#define ElemType int
#define Status int
#define ERROR 0
#define OK 1
using namespace std;
typedef struct LNode {
ElemType data;
struct LNode *next;
}LNode,*LinkedList;
//算法2.8 查找结点
Status GetElem_L(LinkedList L, int i, ElemType &e)
{
LNode *p = L->next;
int j = 1;
while (p&&j < i)
{
p = p->next;
++j;
}
if (!p || j > i)
return ERROR;
e = p->data;
return OK;
}
//算法2.9 添加结点
Status ListInsert_L(LinkedList &L, int i, ElemType e)
{
LNode *p = L;
int j = 0;
while (p&&j < i - 1)
{
p = p->next;
++j;
}
if (!p || j > i - 1)
return ERROR;
LNode *s = (LinkedList)malloc(sizeof(LNode));
s->data = e;
s->next = p->next;
p->next = s;
return OK;
}
//算法2.10 删除结点
Status ListDelete_L(LinkedList &L, int i, ElemType &e)
{
LNode *p=L;
int j = 0;
do
{
p = p->next;
++j;
} while (j<i-1||!p);
if (!(p->next) || j > i - 1)
return ERROR;
LNode *q = p->next;
p->next = q->next;
e = q->data;
free(q);
return OK;
}
//逆位序创建线性表,算法2.11
void CreateList_L(LinkedList &L, int n)
{
L= (LinkedList)malloc(sizeof(LNode));
L->next = NULL;
for (int i = n; i > 0; --i)
{
LNode *q = (LinkedList)malloc(sizeof(LNode));
cin >> q->data;
q->next = L->next;
L->next = q;
}
}
void PrintList_L(LinkedList &L)
{
LNode *p = L->next;
while (p)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
void main()
{
LinkedList L;
int number;
cout << "输入线性表元素个数:";
cin >> number;
CreateList_L(L, number);
cout << "线性表:" << endl;
PrintList_L(L);
int Get_Number,Elem=0;
cout << "输入查询第几个元素:";
cin >> Get_Number;
int Get_Elem = GetElem_L(L, Get_Number, Elem);
if (Get_Elem)
{
cout << "所查询的元素:" <<Elem<<endl;
}
else
{
cout << "第" << Get_Number << "个元素不存在" << endl;
}
int InsertNumber;
cout << "插入的元素值:";
cin >> InsertNumber;
cout << "插入第几个位置:" << endl;
int InNum;
cin >> InNum;
Status Insert = ListInsert_L(L,InNum, InsertNumber);
if (Insert)
{
cout << "插入成功" << endl;
cout << "线性表如下:" << endl;
PrintList_L(L);
cout << endl;
}
else
{
cout << endl;
cout << "未插入成功" << endl;
}
int DeleteNumber,Delete_Elem=0;
cout << "删除的元素位置:";
cin >> DeleteNumber;
Status Delete = ListDelete_L(L, DeleteNumber, Delete_Elem);
if (Delete)
{
cout << endl;
cout << "删除的值:" << Delete_Elem << endl;
cout << "新的线性表:" << endl;
PrintList_L(L);
}
else
{
cout << "删除失败" << endl;
}
system("pause");
}