之前因为面试,写了不少次的次链表,但是每次写完都觉的还是有很多地方没处理好.这次在没有时间压力下,写了一个自己感觉比较满意的,用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);
}