#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROE 0
#define TRUE 1
#define FALSE 0
typedef int ElemType;
typedef int Status;
typedef struct LNode
{
ElemType data;
struct LNode *next;
}LNode,*LinkList;
Status InitList(LNode *L);
Status PrintList(LinkList L);
Status CreateList(LNode *head);
Status CreateListTail(LNode *head);
Status GetElem(LinkList L,int i,ElemType *e);
LNode *LocateElem(LinkList L,ElemType e);
Status InsertList(LinkList *L,int i,ElemType e);
Status DeleteList(LinkList *L,int i,ElemType *e);
Status ClearList(LinkList *L);
Status InitList(LinkList L)
{
L = (LNode *)malloc(sizeof(LinkList));
if(L == NULL)
{
printf("申请内存空间失败");
}
L->next = NULL;
return OK;
}
Status CreateList(LNode *head)
{
int x;
printf("请输入数值:");
scanf("%d",&x);
while(x != 9999)
{
LNode *node = (LNode *) malloc(sizeof(LNode));
node->data = x;
node->next = head->next;
head->next = node;
scanf("%d",&x);
}
return OK;
}
Status CreateListTail(LNode *head)
{
int x;
LNode *t = head;
printf("请输入尾插法插入的数值:");
scanf("%d",&x);
while(x != 9999)
{
LNode *node = (LNode *) malloc(sizeof(LNode));
node->data = x;
t->next = node;
t = node;
scanf("%d",&x);
}
t->next = NULL;
return OK;
}
Status GetElem(LinkList L,int i,ElemType *e)
{
int j = 1;
LNode *p = L->next;
while(p != NULL && j<i)
{
p = p->next;
j++;
}
if(!p || j > i)
{
return ERROE;
}
*e = p->data;
return OK;
}
LNode *LocateElem(LinkList L,ElemType e)
{
LNode *p = L->next;
while(p != NULL && p->data != e)
{
p = p->next;
}
return p;
}
Status InsertList(LinkList *L,int i,ElemType e)
{
int j = 1;
LNode * p = *L;
while(p != NULL && j < i)
{
p = p->next;
j++;
}
if(!p || j > i)
return ERROE;
LNode *s = (LNode *)malloc(sizeof(LNode));
s->data = e;
s->next = p->next;
p->next = s;
return OK;
}
Status DeleteList(LinkList *L,int i,ElemType *e)
{
int j=1;
LNode *p = *L;
while(p ->next && j<i)
{
p = p->next;
j++;
}
if(!(p->next) || j>i)
{
return ERROE;
}
LNode *q = p->next;
*e = q->data;
p->next = q->next;
free(q);
return OK;
}
Status ClearList(LinkList *L)
{
LNode *p,*q;
p = (*L)->next;
while(p)
{
q = p->next;
free(p);
p = q;
}
(*L)->next = NULL;
return OK;--
}
Status PrintList(LinkList L)
{
LNode *nextnode = L->next;
while(NULL != nextnode)
{
printf("%d ",nextnode->data);
nextnode = nextnode->next;
}
printf("\n");
return OK;
}
int main()
{
int e;
LNode *head = (LNode *) malloc(sizeof(LNode));
head->next = NULL;
CreateListTail(head);
PrintList(head);
InsertList(&head,3,6);
printf("插入元素后的链表为");
PrintList(head);
DeleteList(&head,2,&e);
printf("删除元素后的链表为");
PrintList(head);
ClearList(&head);
if(1 == ClearList(&head))
{
printf("清空链表成功!!");
}
}