//线性表---链表的基本操作
#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define NULL 0
typedef int Status; //函数结果状态代码
typedef int ElemType; //数据元素类型
//------线性表的单链表存储结构--------
typedef struct LNode
{
ElemType data; //数据域
struct LNode *next; //指针域
}LNode,*LinkList;
//------逆序输入n个元素的值,创建一个带头结点的单链表L
void CreatList_L(LinkList &L,int n)
{
int i;
LNode *p;
L = (LinkList)malloc(sizeof(LNode));
L->data = 0; //令头结点中的数据域内容为0(即表的长度为0),头结点中的数据域记录了表的长度
L->next = NULL; //建立一个带头结点的单链表L
printf("Please input data:\n");
for(i = n;i>0;--i)
{
p = (LinkList)malloc(sizeof(LNode)); //生成新结点
scanf("%d",&p->data);
p->next = L->next;
L->next = p; //新结点插入到表头
L->data++; //增加表长
}
}//CreatList_L
//------带表头结点的单链表L的查找
Status GetElem_L(LinkList L,int i,ElemType &e)
{
LNode *p;
int j;
p = L->next;
j = 1;
while(p && j<i)
{
p = p->next;
++j;
}
if(!p || j>i)
return ERROR; //第i个元素不存在
e = p->data;
return OK;
}//GetElem_L
//------带表头结点的单链表L的插入
Status ListInsert_L(LinkList &L,int i,ElemType e)
{
LNode *p,*s;
int j;
p = L;
j = 0;
while(p && j<i-1)
{
p = p->next;
j++;
}
if(!p || j>i-1)
return ERROR;
s = (LinkList)malloc(sizeof(LNode)); //产生新的结点
s->data = e;
s->next = p->next;
p->next = s;
L->data++; //增加表的长度
return OK;
}//ListInsert_L
//------带表头结点的删除
Status ListDelete_L(LinkList &L,int i,ElemType &e)
{
LNode *p,*q;
int j = 0;
p = L;
while(p->next && j<i-1)
{//寻找第i个结点,并令p指向其前驱
p = p->next;
++j;
}
if(!(p->next) || j>i-1)
return ERROR;
q = p->next;
p->next = q->next;
e = q->data;
free(q); //释放结点q
L->data--; //表长减一
return OK;
}//ListDelete_L
//------带表头结点的遍历
Status Traverse_L(LinkList L)
{
LNode *p = L->next;
printf("This list contains %d elements\n",L->data);
while(p) //不能写成while(p->next)
{
printf("%5d->",p->data);
p = p->next;
}
printf("NULL\n");
return OK;
}//Traverse_L
//------求带表头结点的单链表的表长
int Length_L(LinkList L)
{
int num = 0;
LNode *p = L->next;
while(p)
{
num++;
p = p->next;
}
return num;
}//Length_L
//------删除元素递增排列的带头结点的链表L中值大于mink小于maxk的所有元素
Status Delete_Between(LinkList &L,int mink,int maxk)
{
LinkList p,q;
p = L;
while(p->next && p->next->data<=mink)
p = p->next; //p是最后一个不大于mink的元素
if(p->next)
{
q = p->next;
while(q->data<maxk)
q = q->next; //q是第一个不小于maxk的元素
p->next = q;
}
return OK;
}
int main()
{
LinkList L;int n,i,i1,i2,e,e1,e2,j1,j2;
printf("Please input the number in the list:");
scanf("%d",&n);
CreatList_L(L,n);
Traverse_L(L);
printf("the length is:%d\n",Length_L(L));
printf("Get elem i:");
scanf("%d",&i);
GetElem_L(L,i,e);
printf("the NO.%d elem is:%d\n",i,e);
printf("Insert position:");
scanf("%d",&i1);
printf("Insert number:");
scanf("%d",&e1);
ListInsert_L(L,i1,e1);
Traverse_L(L);
printf("Delete position:");
scanf("%d",&i2);
ListDelete_L(L,i2,e2);
Traverse_L(L);
printf("\nDelete between(a,b):");
scanf("%d%d",&j1,&j2);
printf("the results:%d\n",Delete_Between(L,j1,j2));
Traverse_L(L);
printf("\n");
return 0;
}