#include <stdio.h>
#include <stdlib.h>
#define ERROR 0 //宏定义
#define OK 1
typedef int Status; //自定义数据类型
typedef int ElemType;
typedef struct node{ //单链表的类型定义
ElemType element; //节点的数据域
struct node *link; //节点的指针域
}Node;
typedef struct sigleList{
Node *first; //头指针
int n; //单链表中元素个数
}SingleList;
Status Init(SingleList *L){ //单链表的初始化
L->first=NULL;
L->n=0;
return OK;
}
Status Find(SingleList *L,int i,ElemType *x){ //单链表的查找
Node *p;
int j;
if(i<0 || i>L->n-1) //对i进行越界检查
return ERROR;
p=L->first;
for(j=0;j<i;j++) //从头结点开始查找ai
p=p->link;
*x=p->element; //通过x返回ai的值
return OK;
}
Status Insert(SingleList *L,int i,ElemType x){ //单链表的插入
Node *p,*q;
int j;
if(i<-1 || i>L->n-1)
return ERROR;
p=L->first;
for(j=0;j<i;j++)
p=p->link; //从头结点开始查找ai
q=(Node *)malloc(sizeof(Node)); //生成新结点q
q->element=x;
if(i>-1){
q->link=p->link; //新节点插在p所指结点之后
p->link=q;
}
else{
q->link=L->first; //新结点插在头结点之前,成为新的头结点
L->first=q;
}
L->n++;
return OK;
}
Status Delete(SingleList *L,int i){ //单链表的删除
Node *p,*q;
int j;
if(!L->n)
return ERROR;
if(i<0 || i>L->n-1)
return ERROR;
q=L->first;
p=L->first;
for(j=0;j<i;j++)
q=q->link;
if(i==0)
L->first=L->first->link; //删除的是头结点
else{
p=q->link; //p指向ai
q->link=p->link; //从单链表中删除p所指向的结点
}
free(p); //释放p结点所指向的存储空间
L->n--;
return OK;
}
Status Output(SingleList *L){ //单链表的输出
Node *p;
if(!L->n) //判断顺序表是否为空
return ERROR;
p=L->first;
while(p){
printf("%d ",p->element);
p=p->link;
}
return OK;
}
void Destory(SingleList *L){ //单链表的撤销
Node *p;
while(L->first){
p=L->first->link; //保存后继结点的地址,防止断链
free(L->first); //释放first所指结点的存储空间
L->first=p;
}
}
Status PreNode(SingleList *L,ElemType x){ //已知某个结点的数据是x,遍历返回其前驱结点的值
if(L->first==NULL || L->n==0)
return ERROR;
Node *p,*q; //定义两个结点指针
q=L->first; //q指向L链表的头结点
p=q->link; //p指向头结点的后继节点
while(p){
if(p->element==x)
return q->element; //直接将x的前驱结点返回
q=q->link; //q指针后移
p=q->link; //p指针指向q的后继结点
}
return OK;
}
void main(){
SingleList list; //定义list链表
Init(&list); //初始化list链表
for(int i=0;i<9;i++) //将0--9存入list链表中
Insert(&list,i-1,i);
printf("the linklist is:");
Output(&list);
Delete(&list,0);
printf("\nthe linklist is:");
Output(&list);
int x;
Find(&list,4,&x); //查找下标为4的结点并返回其数据域的值
printf("\nthe value is:");
printf("%d\n",x);
int y=8;
printf("the precursor node of %d is:%d\n",y,PreNode(&list,y));
Destory(&list);
system("pause");
}
09-21
09-15
09-15