递归实现和非递归
#include <iostream>
using namespace std;
//结点
struct Node
{
int value;
Node* next;
};
//尾插法
Node* create_list(int v, int len)
{
Node* ret = NULL;
Node* slider = NULL;
for(int i=0; i<len; i++)
{
Node* n = new Node();
n->value = v++;//头结点
n->next = NULL;
if(slider == NULL)
{
slider = n;//slider和头结点挂接
ret = n;//ret指向头结点
}
else
{
slider->next = n; //尾插法
slider = n;//移动slider指向新插入的结点
}
}
return ret;//返回链表头结点
}
void destory_list(Node* list)
{
while(list)
{
Node* del = list;
list = list->next;
delete del;
}
}
void print_list(Node* list)
{
while(list)
{
cout << list->value << "->";
list = list->next;
}
cout << "NULL" << endl;
}
//递归实现
int listLength(Node* list)
{
if(list == NULL)
return 0;
else
return 1 + listLength(list->next);
}
int listLength_non(Node* list)
{
int n = 0;
while(list)
{
n++;
list = list->next;
}
return n;
}
int main()
{
Node* list = create_list(1, 7);
print_list(list);
cout << listLength_non(list) << endl;
return 0;
}