链表

之前因为面试,写了不少次的次链表,但是每次写完都觉的还是有很多地方没处理好.这次在没有时间压力下,写了一个自己感觉比较满意的,用c++实现的.链表的节点涉及到动态内存的分配,用c++的构造函数实现起来方便多了.还可以用c实现链表节点,struct stru_list改为用函数指针实现,并且不修改链表操作中的接口.

 

 

#include <iostream>
/***********************************************************
desc    :       the linked list mode coded with c++
author  :       wudy
date    :       2009-01-09
************************************************************/

using namespace std;
typedef struct stru_list{
public:

        stru_list(const char* str)
        :p(NULL),next(NULL)
        {
                if(str && strlen(str))
                {
                        p = new char[strlen(str)];
                        strcpy(p, str);
                }
        }

        ~stru_list()
        {
                if(p)
                        delete []p;
        }
public:
        struct stru_list *next;
        char *p;
}list,node;

 

 

list* create_list()
{
        list *h;
        node *Node,*Tmp;
        int i=1;

        cout << "create the list input node info" <<endl;
        string str;
        cin >> str;
        Node = new node(str.c_str());
        Tmp = h = Node;
        cin >> str;
        while( str.c_str()[0] != 0 )
        {
                cout << str << endl;
                Node = new node(str.c_str());
                Tmp->next = Node;
                Tmp = Tmp->next;
                cin >> str;
        }
        return h;
}

void delete_list(list *h)
{
        node *Node;
        while( h->next != NULL)
        {
                Node = h;
                h=h->next;
                delete Node;
        }
        delete h;
}
void display(list* h)
{
        while(h->next != NULL)
        {
                cout << h->p <<endl;
                h=h->next;
        }
        cout << h->p;

}

void reverse(list* &head)
{
        node *p=NULL,*q=NULL,*t1=NULL;
        p = head;
        if( p->next == NULL)
                return;
        q = p->next;

        if( q->next != NULL)
                t1 = q->next;
        while( t1->next != NULL)
        {
                q->next = p;
                p = q;
                q = t1;
                t1 = q->next;
        }
        t1->next=q;
        q->next=p;
        head->next = NULL;
        head=t1;
}


int
main()
{

        list *head;
        head = create_list();
        display(head);
        reverse(head);
        display(head);
        delete_list(head);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值