![]() |
#2
玩出来的代码2011-08-28 00:50
|

#include <iostream>
using namespace std;
#define OK 1
#define ERROR 0
#define NULL 0
typedef int elemtype;
typedef struct l_node
{
elemtype data;
struct l_node *next;
}l_node, *link_list;
//
elemtype create_list(link_list &_list_head)
{
_list_head = new l_node;
_list_head->data = 0;//当前表长
if( _list_head==NULL )
return ERROR;
else
return OK;
}//
//尾插法
elemtype list_insert(link_list & _list_head, elemtype &elem)
{
link_list q = new l_node;
q->data = elem;
q->next = NULL;
if(_list_head->next == NULL)
{
_list_head->next = q;
++(_list_head->data);
return OK;
}
else
{
link_list p = NULL;
p = _list_head->next;
while(p->next != NULL)
{
p = p->next;
}
p->next = q;
++(_list_head->data);
return OK;
}
}//
//
void print_list(link_list &_list_head)
{
link_list p=NULL;
p = _list_head;
while(p->next != NULL)
{
cout<<"当前表长:"<<_list_head->data<<endl;
cout<<"当前表元素:";
cout<<p->data<<ends<<ends;
p = p->next;
}
}//
int main(int argc, char *argv[])
{
link_list head = NULL;
create_list(head);
while(true)
{
elemtype e;
cout<<"输入插入元素:";
cin>>e;
list_insert(head, e);
print_list(head);
}
return 0;
}
我总觉得动态内存分配不正确,可是又不知道是哪儿出现了错误,帮我看看吧,谢谢 using namespace std;
#define OK 1
#define ERROR 0
#define NULL 0
typedef int elemtype;
typedef struct l_node
{
elemtype data;
struct l_node *next;
}l_node, *link_list;
//
elemtype create_list(link_list &_list_head)
{
_list_head = new l_node;
_list_head->data = 0;//当前表长
if( _list_head==NULL )
return ERROR;
else
return OK;
}//
//尾插法
elemtype list_insert(link_list & _list_head, elemtype &elem)
{
link_list q = new l_node;
q->data = elem;
q->next = NULL;
if(_list_head->next == NULL)
{
_list_head->next = q;
++(_list_head->data);
return OK;
}
else
{
link_list p = NULL;
p = _list_head->next;
while(p->next != NULL)
{
p = p->next;
}
p->next = q;
++(_list_head->data);
return OK;
}
}//
//
void print_list(link_list &_list_head)
{
link_list p=NULL;
p = _list_head;
while(p->next != NULL)
{
cout<<"当前表长:"<<_list_head->data<<endl;
cout<<"当前表元素:";
cout<<p->data<<ends<<ends;
p = p->next;
}
}//
int main(int argc, char *argv[])
{
link_list head = NULL;
create_list(head);
while(true)
{
elemtype e;
cout<<"输入插入元素:";
cin>>e;
list_insert(head, e);
print_list(head);
}
return 0;
}