[C++] 纯文本查看 复制代码 //
// main.cpp
// Hello
//
// Created by 余西安 on 16/5/19.
// Copyright © 2016年 Sian. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Object{
int i;
char name[10];
Object *next;
};
Object *m_head = (Object *)malloc(sizeof(Object));
// 链表头部追加对象
void sa_add(Object *obj){
Object *p = m_head;
obj->next = p->next;
p->next = obj;
}
void add(Object *obj){
Object *p = m_head;
while (p->next) {
p = p->next;
}
p->next = obj;
obj->next = NULL;
}
int main(){
m_head->next = NULL;
while(true){
char cmd[10];
printf(">");
scanf("%s", cmd);
if(strcmp(cmd, "add") == 0){
Object *obj = (Object *)malloc(sizeof(Object));
printf("ID:");
scanf("%d", &obj->i);
printf("Name:");
scanf("%s", obj->name);
add(obj);
continue;
}
if (strcmp(cmd, "list") == 0){
Object *p = m_head->next;
while (p) {
printf("%d - %s\n", p->i, p->name);
p = p->next;
}
continue;
}
if (strcmp(cmd, "exit") == 0){
printf("Bye!\n");break;
}
printf("Error Code!\n");
}
return 0;
} 运行结果:[C++] 纯文本查看 复制代码 >list
>add
ID:1
Name:admin
>list
1 - admin
>add
ID:2
Name:sian
>list
1 - admin
2 - sian
>exit
Bye!
Program ended with exit code: 0
|