单链表
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
typedef int Status;
typedef int ElemType;
typedef struct LNode{
ElemType data;
struct LNode *next;
}LNode,*LinkList;
Status InitList(LinkList *L)
{
*L = (LinkList)malloc(sizeof(LNode));
(*L)->next = NULL;
return OK;
}
Status GetElem(LinkList L, int i, ElemType *e)
{
int j=1;
LinkList p = L->next;
while (p && j<i)
{
p = p->next;
++j;
}
if (!p || j>i){
return ERROR;
}
*e = p->data;
return OK;
}
LNode* LocateElem(LinkList L, ElemType e)
{
LinkList p = L->next;
while (p&&p->data != e)
{
p = p->next;
}
return p;
}
int LocateElem_Pro(LinkList L, ElemType e)
{
int j = 1;
LinkList p = L->next;
while (p&&p->data != e)
{
p = p->next;
j++;
}
if (p){
return j;
} else{
return 0;
}
}
Status ListInsert(LinkList *L, int i, ElemType e)
{
int j = 0;
LinkList p = *L,s;
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;
return OK;
}
Status ListDelete(LinkList *L, int i, ElemType *e)
{
int j = 0;
LinkList p = *L, q;
while (p->next && j < i-1)
{
p = p->next;
++j;
}
if (!(p->next) || j > i - 1){
return ERROR;
}
q = p->next;
p->next = q->next;
*e = q->data;
free(q);
return OK;
}
void CreateList_H(LinkList *L, int n)
{
*L = (LinkList)malloc(sizeof(LNode));
(*L)->next = NULL;
LNode* p;
for (int i = 0; i<n; i++)
{
p = (LNode*)malloc(sizeof(LNode));
scanf("%d",&(p->data));
p->next = (*L)->next;
(*L)->next = p;
}
}
void CreateList_R(LinkList *L, int n)
{
*L = (LinkList)malloc(sizeof(LNode));
(*L)->next = NULL;
LinkList p, r;
r = *L;
for (int i = 0; i<n; i++)
{
p = (LNode *)malloc(sizeof(LNode));
scanf("%d", &(p->data));
p->next = NULL;
r->next = p;
r = p;
}
}
Status ListEmpty(LinkList L)
{
if (L->next){
return FALSE;
}else {
return TRUE;
}
}
Status DestroyList(LinkList *L){
LNode *p;
while (*L){
p = *L;
*L = (*L)->next;
free(p);
}
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;
}
int ListLength(LinkList L){
LinkList p = L->next;
int i = 0;
while (p){
i++;
p = p->next;
}
return i;
}
Status visit(ElemType c)
{
printf("%d ", c);
return OK;
}
Status ListTraverse(LinkList L)
{
LinkList p = L->next;
while (p)
{
visit(p->data);
p = p->next;
}
printf("\n");
return OK;
}
void main(){
LinkList L;
ElemType e;
CreateList_H(&L, 5);
printf("【头插法】插入后单链表的值:");
ListTraverse(L);
printf("【头插法】插入后单链表长度:%d \n\n", ListLength(L));
ClearList(&L);
CreateList_R(&L, 5);
printf("【尾插法】插入后单链表的值:");
ListTraverse(L);
printf("【尾插法】插入后单链表长度:%d \n\n", ListLength(L));
e = 66;
ListInsert(&L, 4, e);
printf("位序4插入后单链表的值:");
ListTraverse(L);
GetElem(L, 4, &e);
printf("\n位序4获取到的元素值:%d\n\n", e);
ListDelete(&L, 4, &e);
printf("删除位序4后单链表的值:");
ListTraverse(L);
DestroyList(&L);
if (L==NULL){
printf("\n销毁完成!L=NULL\n");
}
system("pause");
}
|