线性表L采用链式存储结构linklist,实现求线性表元素位序操作:
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
using namespace std;
#define error 0
#define ok 1
#define overflow -2
typedef int status;
typedef char elemtype;
typedef struct lnode{
elemtype data;//数据域
struct lnode *next;//指针域
}lnode, *linklist;
//初始化链表
status initlist(linklist & l) {
lnode * temp;
temp = (lnode* )malloc(sizeof(lnode));
if(!temp) exit(overflow);
l = temp;
l->next =NULL;
return ok;
}
//输入(尾部插入)链表
status inputlist(linklist & l) {
lnode * curPtr, * rearPtr;
int n;
cin>>n;
rearPtr = l; //初始时头结点为尾节点,rearPtr指向尾巴节点
for (int i = 1;i <= n;i ++){ //每次循环都开辟一个新节点,并把新节点拼到尾节点后
curPtr = (lnode*)malloc(sizeof(lnode));//生成新结点
if(!curPtr) exit(overflow);
scanf(" %c",&curPtr->data);//输入元素值
curPtr->next = NULL; //最后一个节点的next赋空
rearPtr->next = curPtr;
rearPtr = curPtr;
}
return ok;
}
//销毁链表
void destroylist(linklist &l) {
linklist p = l;
while (p)
{
l = l->next;
delete(p);
p = l;
}
}
/*
status locateelem(linklist l,elemtype &e){
linklist p;
p=l->next;
int j=1;
while(p&&p->data!=e){
p=p->next;
j++;
}
if(p) return ok;
else return error;
}*/
status listlength(linklist &l)
{
linklist p=l;int sum=0;
while(p)
{
sum++;
p=p->next;
}
return sum-1;//去除头结点
}
int locateelem(linklist l, elemtype e)
{
int j = 1;
lnode* p = l->next;
while(p != NULL && p->data != e)
{
p = p->next;
j++;
}
if(j == listlength(l))
{
return 0;
}
return j;
}
int main()
{
linklist l;int order;elemtype e;
initlist(l);
inputlist(l);
// printf("please input e:");
scanf("%d",&e);
order=locateelem(l,e);
if(order) printf("%d\n",order);
else printf("error");
destroylist(l);
return 0;
}