欢迎关注,大家共同学习!
上一篇介绍了线性表的顺序存储结构和基于数组的实现,这篇介绍线性表的链式存储结构。
链式存储:用一组任意的存储单元存储线性表中的元素;
特点:
(1)存储单元可以是连续的,也可以是零散的;
(2)链表中结点的物理顺序和逻辑顺序不一定相同。
由于存储单元不一定是连续的,为了正确的表示结点之间的逻辑关系,每个结点除了存储数据信息外,还需要存储结点的直接后继结点的地址,我们称之为链或指针。
1、结点的定义:
typedef struct Lnode
{
ElemType data;
struct Lnode *next;
}LNode;
2、初始化
int LinkList_Init(LNode *head)
{
head->data=0;
head->next=NULL;
return OK;
}
3、表的插入操作
int LinkList_Insert(LNode *head,int i,ElemType e)
{
int flag=0;
LNode *p,*pre,*q;
pre=head;
p=head->next;
flag++;
while(flag<i)
{
pre=p;
p=p->next;
flag++;
}
q=(LNode *)malloc(sizeof(LNode));
q->data=e;
pre->next=q;
q->next=p;
return OK;
}
4、表的删除操作
int LinkList_Delete(LNode *head,int i,ElemType *x)
{
int flag=0;
LNode *pre,*p;
pre=head;
p=head->next;
flag++;
while(flag<i)
{
pre=p;
p=p->next;
flag++;
}
*x=p->data;
pre->next=p->next;
return OK;
}
5、获取表的长度
int LinkList_getLength(LNode *head)
{
int counter=0;
LNode *p;
p=head;
while(!p)
{
counter++;
p=p->next;
}
return counter;
}
6、获取表尾元素
int LinkList_getLastData(LNode *head)
{
ElemType temp;
LNode *p;
p=head;
while(p->next)
{
p=p->next;
}
temp=p->data;
return temp;
}
7、打印元素
int LinkList_print(LNode *head)
{
LNode *p;
p=head->next;
cout<<"打印结果:"<<endl;
while(p)
{
cout<<p->data<<endl;
p=p->next;
}
return OK;
}
关于链式存储结构的线性表结构的定义和全部操作就是上述这些,最后给出全部测试代码:
#include <iostream>
#include<malloc.h>
#define OK 1
#define ERROR -1
typedef int ElemType;
using namespace std;
//
typedef struct Lnode
{
ElemType data;
struct Lnode *next;
}LNode;
//
int LinkList_Init(LNode *head)
{
head->data=0;
head->next=NULL;
return OK;
}
//
int LinkList_getLength(LNode *head)
{
int counter=0;
LNode *p;
p=head;
while(!p)
{
counter++;
p=p->next;
}
return counter;
}
//insert
int LinkList_Insert(LNode *head,int i,ElemType e)
{
int flag=0;
LNode *p,*pre,*q;
pre=head;
p=head->next;
flag++;
while(flag<i)
{
pre=p;
p=p->next;
flag++;
}
q=(LNode *)malloc(sizeof(LNode));
q->data=e;
pre->next=q;
q->next=p;
return OK;
}
//
int LinkList_Delete(LNode *head,int i,ElemType *x)
{
int flag=0;
LNode *pre,*p;
pre=head;
p=head->next;
flag++;
while(flag<i)
{
pre=p;
p=p->next;
flag++;
}
*x=p->data;
pre->next=p->next;
return OK;
}
//
int LinkList_getLastData(LNode *head)
{
ElemType temp;
LNode *p;
p=head;
while(p->next)
{
p=p->next;
}
temp=p->data;
return temp;
}
int LinkList_print(LNode *head)
{
LNode *p;
p=head->next;
cout<<"打印结果:"<<endl;
while(p)
{
cout<<p->data<<endl;
p=p->next;
}
return OK;
}
int main()
{
LNode *head;
ElemType x_delete;
head=(LNode *)malloc(sizeof(LNode));
LinkList_Init(head);
for(int i=0;i<10;i++)
LinkList_Insert(head,i+1,i);
LinkList_print(head);
LinkList_Delete(head,5,&x_delete);
cout<<"删除的元素:"<<x_delete<<endl;
cout<<"获得表尾元素:"<<LinkList_getLastData(head)<<endl;
cout<<"打印操作后的元素:"<<endl;
LinkList_print(head);
return 0;
}