重新教自己学算法之单向链表(九)

来源:互联网 发布:人民币国际化指数数据 编辑:程序博客网 时间:2024/05/22 17:41
#include <iostream>#include <cstdlib>#include <cassert>#include <cstring>using namespace std;#define STATUS int#define TRUE 1#define FALSE 0typedef struct _LINK_NODE{    int data;    struct _LINK_NODE* next;}LINK_NODE;LINK_NODE* alloca_node(int value){    LINK_NODE* pLinkNode = NULL;    pLinkNode = (LINK_NODE*)malloc(sizeof(LINK_NODE));    pLinkNode->data = value;    pLinkNode->next = NULL;} //删除整个链表void delete_node(LINK_NODE** pNode){    LINK_NODE** pNext;    if(NULL == pNode || NULL == *pNode)        return ;    pNext = &((*pNode)->next);    free(*pNode);    delete_node(pNext);}STATUS _add_data(LINK_NODE** pNode, LINK_NODE* pDataNode){    if(NULL == *pNode)    {        *pNode = pDataNode;        return TRUE;    }    return _add_data(&(*pNode)->next, pDataNode);}STATUS add_data( LINK_NODE** pNode, int value){    LINK_NODE* pDataNode;    if(NULL == *pNode)        return FALSE;    pDataNode = alloca_node(value);    assert(NULL != pDataNode);    return _add_data((LINK_NODE**)pNode, pDataNode);}STATUS _delete_data(LINK_NODE** pNode, int value){    LINK_NODE* pLinkNode;    if(NULL == (*pNode)->next)        return FALSE;    pLinkNode = (*pNode)->next;    if(value == pLinkNode->data)    {        (*pNode)->next = pLinkNode->next;        free(pLinkNode);        return TRUE;    }    else    {        return _delete_data(&(*pNode)->next, value);    }}STATUS delete_data(LINK_NODE** pNode, int value){    LINK_NODE* pLinkNode;    if(NULL == pNode || NULL == *pNode)        return FALSE;    if(value == (*pNode)->data)    {        pLinkNode = *pNode;        *pNode = pLinkNode->next;        free(pLinkNode);        return TRUE;    }    return _delete_data(pNode, value);}LINK_NODE* find_data(const LINK_NODE* pLinkNode, int value){    if(NULL == pLinkNode)        return NULL;    if(value == pLinkNode->data)    {        return (LINK_NODE*)pLinkNode;    }    return find_data(pLinkNode->next ,value);   }void print_node(const LINK_NODE* pLinkNode){    if(pLinkNode)    {        cout<<pLinkNode->data<<"  ";        print_node(pLinkNode->next);    }    cout<<endl;}int count_node(const LINK_NODE* pLinkNode){    if(NULL == pLinkNode)        return 0;    return 1 + count_node(pLinkNode->next); }int main(){    LINK_NODE* pLinkNode = alloca_node(10);    LINK_NODE** pNode = &pLinkNode;    add_data(pNode,15);    add_data(pNode,20);    cout<<pLinkNode<<endl;    cout<<pLinkNode->next<<endl;    cout<<pLinkNode->next->next<<endl;    cout<<*pNode<<endl;        //pNode里存放的是链表的首地址    // print_node(pLinkNode);    // delete_data(pNode,15);    // print_node(pLinkNode);    // print_node(pLinkNode);    // cout<<pLinkNode<<endl;    // cout<<&(*pNode)->next<<endl;}
0 0