单向链表

/*
 *此程序使用c++语言模拟单向链表的工作原理
 *主要具有对向链表中插入数据、删除链表数据、浏览链表中所有数据的功能
 *
 *Author: StoryMonster
 *last change date: 2016/06/22
 */

#include <stdlib.h>
#include <iostream>

typedef struct aa
{
    int value;
    struct aa *next;
} ChainTable;

ChainTable *head = NULL;
int CurrentLength = 0;  //当前链表长度
/*
 *向链表插入数据
 *返回值是插入数据后在新链表的位置
 */
int InsertChainTable(ChainTable *chain)
{
    ChainTable *p = (ChainTable *)malloc(sizeof(ChainTable));
    if(head == NULL)
    {
        head = chain;
        CurrentLength++;
        return CurrentLength;
    }
    p = head;
    while(p->next != NULL)
    {
        p = p->next;
    }
    p->next = chain;
    CurrentLength++;
    return CurrentLength;
}

void ScanChainTable()
{
    ChainTable *p = (ChainTable *)malloc(sizeof(ChainTable));
    p = head;
    while(p->next != NULL)
    {
        std::cout << p->value << "-->";
        p = p->next;
    }
    std::cout <<p->value << std::endl; 
}
int DeleteChainTable(int value)
{
    if(head == NULL) return 0;
    ChainTable *p = head->next;
    ChainTable *p1 = head;
    while(p != NULL)
    {
        if(p->value == value)
        {
            p1->next = p->next;
            p->next = NULL;
            free(p);
            return 1;
        }
        p1 = p;
        p = p->next;
    }
    return 0;
}
int main()
{
    head = NULL;
    short choice = 1;
    short insertChoice = 1;
    int value = 0;
    ChainTable *chain = NULL;
    while(1)
    {
        std::cout << "1:insert  2:delete  3:scan" << std::endl;
        std::cout << "your choice:";
        std::cin >> choice;
        switch(choice)
        {
            case 1:chain = (ChainTable *)malloc(sizeof(ChainTable));
                   std::cout << "input value:";
                   std::cin >> chain->value;
                   chain->next = NULL;
                   InsertChainTable(chain);
                   break;
            case 2:std::cout << "delete value:";
                   std::cin >> value;
                   if(DeleteChainTable(value) == 0)
                   {
                       std::cout << "cannot find this value in chain!" << std::endl;
                   }
                   else
                       std::cout << "delete successed!" << std::endl;
                   break;
            case 3:ScanChainTable();
                   break;
            default:break;
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值