本文主要是介绍Acm Club 1326:算法2-8~2-11:链表的基本操作,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目描述
输入格式
输出
样例输入
3 3 2 1
21
show
delete 1
show
delete 2
show
delete 1
show
delete 2
insert 2 5
show
insert 1 5
show
insert 1 7
show
insert 2 5
show
insert 3 6
show
insert 1 8
show
get 2
样例输出
1 2 3
delete OK
2 3
delete OK
2
delete OK
Link list is empty
delete fail
insert fail
Link list is empty
insert OK
5
insert OK
7 5
insert OK
7 5 5
insert OK
7 5 6 5
insert OK
8 7 5 6 5
7
就是用链表来操作,直接上代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0typedef int Status;typedef int Elemtype;typedef struct Node{Elemtype elem;struct Node *next;
}Node, *Linklist;Status visit(Elemtype e)
{printf("%d", e);return OK;
}Status InitLinklist(Linklist *L)
{*L = (Linklist)malloc(sizeof(Node));if(!(*L)) return ERROR;(*L)->next = NULL;return OK;
}Status ListInsert(Linklist *L, int i, Elemtype e)
{int j = 1;Linklist p, s;p = *L;while(p && j < i){p = p->next;++j;}if(!p || j > i) return ERROR;s = (Linklist)malloc(sizeof(Node));s->elem = e;s->next = p->next;p->next = s;return OK;
}Status ListDelete(Linklist *L, int i, Elemtype *e)
{int j = 1;Linklist p, q;p = *L;while(p->next && j < i){p = p->next;++j;}if(!(p->next) || j > i)return ERROR;q = p->next;p->next = q->next;*e = q->elem;free(q);return OK;
}int ListLength(Linklist L)
{int i;Linklist p;i = 0;p = L->next;while(p){i++;p = p->next;}return i;
}Status ListEmpty(Linklist L)
{if(L->next) return FALSE;else return TRUE;
}Status ClearList(Linklist *L)
{Linklist p, q;p = (*L)->next;while(p){q = p->next;free(p);p = q;}(*L)->next = NULL;return OK;
}Status GetElem(Linklist L, int i, Elemtype *e)
{Linklist p;int j;j = 1;p = L->next;while(p && j < i){++j;p = p->next;}if(!p || j > i) return ERROR;*e = p->elem;return OK;
}int ElemLocate(Linklist L, Elemtype e)
{int i;i = 0;Linklist p;p = L->next;while(p){i++;if(p->elem == e)return i;p = p->next;}return 0;
}Status ListTraverse(Linklist L)
{Linklist p;p = L->next;while(p && p->next != NULL){visit(p->elem);printf(" ");p = p->next;}visit(p->elem);printf("\n");return OK;
}int main()
{Linklist L;InitLinklist(&L);int n;//数字个数int nn;//执行命令条数int num;//每个数字int i = 1;//数字计数单位int j;//循环单位char str[100];//命令语句int loc;//数字位置Elemtype e;scanf("%d", &n);for(j = 0; j < n; j++){scanf("%d", &num);ListInsert(&L, 1, num);}scanf("%d", &nn);for(j = 0; j < nn; j++){scanf("%s", str);if(strcmp (str, "show") == 0){if(ListEmpty(L)){printf("Link list is empty\n");continue;}ListTraverse(L);}else if(strcmp (str, "delete") == 0){scanf("%d", &loc);if(ListDelete(&L, loc, &e))printf("delete OK\n");elseprintf("delete fail\n");}else if(strcmp (str, "get") == 0){scanf("%d", &loc);if(GetElem (L, loc, &e)){printf("%d\n", e);}elseprintf("get fail");}else if(strcmp (str, "insert") == 0){scanf("%d%d", &loc, &num);if(ListInsert (&L, loc, num))printf("insert OK\n");elseprintf("insert fail\n");}}return 0;
}
这篇关于Acm Club 1326:算法2-8~2-11:链表的基本操作的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!