#include <stdio.h>
#include <stdlib.h>
typedef int tElem;
typedef struct List {
tElem data;
struct List * next;
} List, *pList;
typedef enum Status {
ok = 1,Error = 0
} Status;
Status InitList(List * head)
{
head = (pList) malloc(sizeof(List));
if(head == NULL)
{
printf("空间申请失败!\n");
return Error;
}
head->next = NULL;
return ok;
}
Status ListEmpty(List * head)
{
int count = 0;
pList temp = head->next;
while (temp != NULL)
{
count ++;
temp = temp->next;
}
printf("线性表的长度为:%d\n",count);
}
Status ListHeadInsert(List * head,tElem e)
{
if(head == NULL)
{
return Error;
}
pList temp = (pList) malloc(sizeof(List));
temp->data = e;
temp->next = head->next;
head->next = temp;
return ok;
}
Status ListTailInsert(List * head,tElem e)
{
if(head == NULL)
{
return Error;
}
pList item = head->next;
pList temp = (pList) malloc(sizeof(List));
temp->data = e;
temp->next = NULL;
while (item->next != NULL)
{
item = item->next;
}
item->next = temp;
return ok;
}
void ListTraverse(List * head)
{
int count = 0;
pList temp = head->next;
while (temp != NULL)
{
count ++;
printf("线性表的第 %d 个元素是:%d\n",count,temp->data);
temp = temp->next;
}
}
Status ListIsIn(List * head,tElem e)
{
pList temp = head->next;
while (temp != NULL)
{
if(temp->data == e)
{
return ok;
}
temp = temp->next;
}
return Error;
}
Status PriorElem(List * head,tElem e)
{
if(!ListIsIn(head,e))
{
printf("元素 %d 不在线性表中!\n",e);
return Error;
}
pList temp = head->next;
if(temp->data == e)
{
printf("元素 %d 是线性表的第一个元素,无前一个元素。\n");
return Error;
}
while (temp->next != NULL)
{
if(temp->next->data == e)
{
printf("元素 %d 的前一个元素是:%d\n",e,temp->data);
return ok;
}
temp = temp->next;
}
}
Status NextElem(List * head,tElem e)
{
if(!ListIsIn(head,e))
{
printf("元素 %d 不在线性表中!\n",e);
return Error;
}
pList temp = head->next;
while (temp->next != NULL)
{
if(temp->data == e)
{
printf("元素 %d 的后一个元素是:%d\n",e,temp->next->data);
return ok;
}
temp = temp->next;
}
if(temp->next == NULL && temp->data == e)
{
printf("元素 %d 是线性表的最后一个元素,没有后一个元素。\n",e);
}
}
Status ListDelete(List * head,tElem e)
{
if(!ListIsIn(head,e))
{
printf("元素 %d 不在线性表中!\n",e);
return Error;
}
pList temp = head->next;
while (temp != NULL)
{
if(temp->data == e)
{
head->next = temp->next;
return ok;
}
if(temp->next->data == e)
{
temp->next = temp->next->next;
return ok;
}
temp = temp->next;
}
}
void ClearList(List * head)
{
head->next = NULL;
}
void DestroyList(List * head)
{
free(head);
printf("销毁成功!\n");
}
int main() {
List head;
InitList(&head);
printf("初始化后:");
ListEmpty(&head);
printf("\n");
ListHeadInsert(&head,10);
ListHeadInsert(&head,20);
ListTailInsert(&head,30);
ListTailInsert(&head,40);
ListTraverse(&head);
printf("\n");
PriorElem(&head,10);
PriorElem(&head,20);
PriorElem(&head,50);
printf("\n");
NextElem(&head,10);
NextElem(&head,40);
NextElem(&head,50);
printf("\n");
ListDelete(&head,50);
ListDelete(&head,30);
ListTraverse(&head);
printf("\n");
ClearList(&head);
printf("清空线性表后:");
ListEmpty(&head);
DestroyList(&head);
return 0;
}
|