#include typedef struct OLNode
{
int data;
struct OLNode * next;
}OLNode;
#define OK 1
#define ERROR 0
#define OVERFLOW -1
#define LEN 5
int InitOLNode(OLNode *L);//初始化单链表
int InsertOLNode(OLNode *L, int e);//创建单链表(插入到尾结点)
int InsertOLNode2(OLNode * L, int i, int e);//结点插入到某位置
int DeleteOLNode(OLNode * L, int i, int e);//删除某结点
int invertOLNode(OLNode L, int a[]);//逆置并输出
int printOLNode(OLNode L);//输出单链表
int main()
{
OLNode L;
int i, e, a[99];
int j = 0;
InitOLNode(&L);
printf("提示:当前单链表的长度为 %d\n\n", LEN);
for (i = 0; i < LEN; i++, j++)
{
printf("请输入 %d 个数据→ ", j+1);
scanf("%d", &e);
InsertOLNode(&L, e);
}
printf("\n操作1:您存入的原始数据,单链表为↓\n");
printOLNode(L);
printf("\n\n操作2:您插入 101 到最后,单链表为↓\n");
InsertOLNode(&L, 101);
printOLNode(L);
DeleteOLNode(&L, 6, 101);
printf("\n\n操作3:您插入 100 到第二个结点后,单链表为↓\n");
InsertOLNode2(&L, 2, 100);
printOLNode(L);
printf("\n\n操作4:您删除第二个结点 100 后,单链表为↓\n");
DeleteOLNode(&L, 2, 100);
printOLNode(L);
printf("\n\n操作5:您逆序排列后,单链表为↓\n");
invertOLNode(L, a);
printf("\n\n");
system("pause");
return 0;
}
int InitOLNode(OLNode * L)//初始化单链表
{
L->data = 0;
L->next = NULL;
return OK;
}
int InsertOLNode(OLNode * L, int e)//创建单链表(插入到尾结点)
{
OLNode * p, * q;
p = L;
q = (OLNode *) malloc(sizeof (OLNode));
if (!q)
{
return OK;
}
q->data = e;
q->next = NULL;
while(p->next)
{
p = p->next;
}
p->next = q;
return OK;
}
int InsertOLNode2(OLNode * L, int i, int e)//结点插入到某位置
{
OLNode * p, * s;
int j = 0;
p = L;
while(p && jnext;
++j;
}
if(!p || j>i-1)
{
return ERROR;
}
s = (OLNode *) malloc(sizeof (OLNode));
s->data = e;
s->next = p->next;
p->next = s;
return OK;
}
int DeleteOLNode(OLNode * L, int i, int e)//删除某结点
{
OLNode * p, * q;
int j = 0;
p = L;
while (p->next && jnext;
++j;
}
if (!(p->next) || j>i-1)
{
return ERROR;
}
q = p->next;
p->next = q->next;
e = q->data;
free(q);
return OK;
}
int invertOLNode(OLNode L, int a[])//逆置
{
OLNode *p;
int i = 0, j;
p = L.next;
while (p)
{
a[i++] = p->data;
p = p->next;
}
for (j=i-1; j>=0; j--)
{
printf("%-5d", a[j]);
}
return OK;
}
int printOLNode(OLNode L)//输出单链表
{
OLNode * p;
p = L.next;
while (p)
{
printf("%-5d", p->data);
p = p->next;
}
return OK;
}