年年有"余"

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 1819|回复: 0

C++中链表的基本实现

[复制链接]
  • TA的每日心情

    2024-10-15 10:05
  • 签到天数: 372 天

    [LV.9]以坛为家II

    发表于 2016-5-20 17:20:06 | 显示全部楼层 |阅读模式
    [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

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    手机版|小黑屋|Archiver|iOS开发笔记 ( 湘ICP备14010846号 )

    GMT+8, 2024-11-22 00:30 , Processed in 0.049737 second(s), 19 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表