单向链表

来源:互联网 发布:js a href click 编辑:程序博客网 时间:2024/06/01 09:45
/* *此程序使用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;}
0 0
原创粉丝点击