您的位置:首页 > 理论基础 > 数据结构算法

链表的实现

2015-09-16 00:51 459 查看
#include<stdio.h>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int Status;
typedef char ElemType;

typedef struct LNode{
ElemType data;
struct LNode* next;
}LNode,*LinkList;

void CreateList_L(LinkList*L,int n)
{
int i;
LNode*p;
*L = (LinkList)malloc(sizeof(LNode));
(*L)->next = NULL;
for(i=n;i>0;--i)
{
p = (LinkList)malloc(sizeof(LNode));
scanf("%c",&p->data);
p->next = (*L)->next;(*L)->next = p;
}
p = (*L)->next;
}//CreateList L

void PrintList_L(LinkList L)
{
LNode*p = L->next;
while(p!=NULL)
{
printf("%c",p->data);
p = p->next;
}
}
//Print all the datas of the LinkList

Status InsertList_L(LinkList*L,int pos,ElemType e)
{
LNode* p = *L,*q;
int i = 0;
while(p!=NULL && i<pos-1)
{
p = p->next;
i++;
}
if(p == NULL || pos-1<i)return ERROR;
q = (LNode*)malloc(sizeof(LNode));
q->data = e;q->next = p->next;
p->next = q;
return OK;
}//Insert a node at the position pos

Status DeleteList_L(LinkList*L,int pos,ElemType*e)
{
LNode*p = *L,*q;
int i = 0;
while(p->next!=NULL && i<pos-1)
{
p = p->next;
i++;
}
if(p->next==NULL || pos-1<i)return ERROR;
q = p->next;
*e = q->data;
p->next = q->next;
free(q);
return OK;
}

int main()
{
LinkList L = NULL;
ElemType e;
CreateList_L(&L,5);
PrintList_L(L);
InsertList_L(&L,3,'9');
printf("\n");
PrintList_L(L);
printf("\n");
DeleteList_L(&L,2,&e);
PrintList_L(L);
printf("\nThe data %c has been deleted!\n",e);
return OK;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构 链表 算法