69,373
社区成员
发帖
与我相关
我的任务
分享
/*
see: http://bbs.csdn.net/topics/391091587
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
struct node
{
int max_count;
int current_count;
int id[100];
char *name[100];
};
typedef struct node *pnode;
//创建一个空的顺序表,最大值为m。n为0
pnode create(int max_count)
{
pnode node = (pnode)malloc(sizeof(struct node));
if (NULL == node) {
printf("failed to create!");
return NULL;
}
node->max_count = max_count;
node->current_count = 0;
printf("success to create\n");
return node;
}
//查询一个表是否为空表
int is_empty(pnode pnode)
{
if (pnode->current_count == 0) {
//printf("empty\n");
return 1;
}
//printf("not empty\n");
return 0;
}
//插入一个信息到顺序表,插入到第index个元素之前
void insert(pnode pnode, int index, int id, char name[10])
{
if (index < 0 || index > pnode->current_count) index = pnode->current_count;
for(int q = pnode->current_count - 1; q >= index; q--) {
pnode->id[q + 1] = pnode->id[q];
pnode->name[q + 1] = pnode->name[q];
}
pnode->current_count++;
pnode->id[index] = id;
//pnode->name[index] = strdup(name); #MinGW's error
pnode->name[index] = (char*)malloc(sizeof(char) * sizeof(strlen(name) + 1));
if (NULL == pnode->name[index]) {
printf("malloc failed.\n");
} else {
strcpy(pnode->name[index], name);
}
//return pnode;
}
int visit(pnode pnode)
{
int i;
if (is_empty(pnode)) return 0;
for (i = 0; i < pnode->current_count; i++) {
printf("%d:[%d, %s] ", i, pnode->id[i], pnode->name[i]);
}
printf("\n");
}
void delete(pnode pnode)
{
int i;
for (i = 0; i < pnode->current_count; i++) {
free(pnode->name[i]);
pnode->name[i] = NULL;
}
pnode->current_count = 0;
}
static void test1()
{
pnode pnode;
char buffer[1024]; // Assume the input string will not exceed 1024.
char name[1024];
int loc = -1;
int id = -1;
int max_count = 10;
int current_count = 0;
pnode = create(max_count);
if (NULL == pnode) return;
while(1) {
printf("Please enter: [name, id, index]. Enter directly to exit.\n");
int index = 0;
for (; (buffer[index] = getchar()) != '\n' && index < 1024; index++) {
//printf("index=%d, buffer[%d]=0x%02x\n", index, index, buffer[index]);
}
//printf("index=%d\n", index);
if (index == 0) {
break;
}
//printf("User's input: %s\n", buffer);
if (3 != sscanf(buffer, "%s %d %d", &name, &id, &loc)) {
printf("Error input. The input should be, e.g., \"John 35 0\"\n");
continue;
}
insert(pnode, loc, id, name);
visit(pnode);
current_count++;
if (current_count == max_count) {
printf("Now is the max count! Stop automatically!\n");
break;
}
}
delete(pnode);
}
int main()
{
test1();
return 0;
}