首页 > 代码库 > 单链表的基本操作

单链表的基本操作

///用26个字母来实现简单的单链表的基本操作
#include<stdio.h>#include<stdlib.h>#define ok 1#define error 0#define MAXSIZE 100typedef int ElemType;typedef int Status;typedef struct node{ ElemType data; struct node *next;} node, *LinkList;void CreatList(LinkList &L)///建立一个单链表{ LinkList r, p; r=L; ///插到表尾 for(int i=0; i<26; i++) { p=(node *)malloc(sizeof(node)); p->data=http://www.mamicode.com/A+i; r->next=p; r=p; } r->next=NULL;}/*for(int i=25; i>=0; i--) { p=(node *)malloc(sizeof(node)); p->data=http://www.mamicode.com/‘A‘+i;>*/Status ListFind(LinkList &L, int i, char *e)///单链表的查找{ LinkList p; p=L->next; int j=1; if(p->next==NULL || j>i)return error; while(p->next && j<i) { p=p->next; j++; } *e=p->data; return ok;}Status ListInsert(LinkList &L, int i, char e)///单链表的删除{ LinkList p, s; p=L; int j=1; if(!p || j>i)return error; while(p && j<i) { p=p->next; j++; } s=(LinkList)malloc(sizeof(node)); s->data=http://www.mamicode.com/e; s->next=p->next; p->next=s; return ok;}Status ListDelete(LinkList &L, int i, char *e)///单链表的插入{ LinkList p, s; p=L; int j=1; if(!p || j>i)return error; while(p && j<i) { p=p->next; j++; } s=p->next; *e=s->data; free(s); return ok;}void traverList(LinkList L)///输出单链表{ LinkList p; p=L->next; while(p) { printf("%c\n", p->data); p=p->next; }}int main(){ int find_index, insert_index, delete_index; char find_char, insert_char[2], delete_char; LinkList L; L=(LinkList)malloc(sizeof(node)); L->next=NULL; CreatList(L);///创建一个单链表 traverList(L);///输出此链表 scanf("%d", &find_index); if(ListFind(L, find_index, &find_char)) printf("输出查找元素: %c\n", find_char); else printf("查找失败\n"); scanf("%d%s", &insert_index, insert_char); if(ListInsert(L, insert_index, insert_char[0])) traverList(L);///输出改变后的单链表 else printf("插入失败\n"); scanf("%d", &delete_index); if(ListDelete(L, delete_index, &delete_char)) printf("输出被删除元素: %c\n", delete_char); else printf("删除失败\n"); return 0;}

 

单链表的基本操作