单向链表基本操作的递归实现
为了熟悉递归的思想,我尝试了采用递归的方式实现单向链表的基本操作。单向的链表是C语言课程中接触到的中比较复杂的数据结构,但是他确实其他数据结构的基础,在一般情况下都是采用迭代的形式实现,迭代的形式相比递归要节省时间和空间,但是代码相对来说要复杂,递归往往只是简单的几句代码,我主要是为了熟悉迭代,并不在性能上进行分析。
基本的实现如下所示:
#include
#include
typedef struct listnode
{
int val;
struct listnode *next;
}List;
/*统计节点个数*/
int count_listnode(List *head)
{
static int count = 0;
if(NULL != head)
{
count += 1;
if(head->next != NULL)
{
count_listnode(head->next);
}
return count;
}
}
/*顺序打印*/
void fdprint_listnode(List *head)
{
if(NULL != head)
{
printf("%d ",head->val);
if(head->next != NULL)
{
fdprint_listnode(head->next);
}
}
}
/*反向打印*/
void bkprint_listnode(List *head)
{
if(head != NULL)
{
if(head->next != NULL)
{
bkprint_listnode(head->next);
}
printf("%d ",head->val);
}
}
/*删除一个节点的数据为d的节点*/
List *delete_node(List * head, int d)
{
List *temp = head;
if(head != NULL)
{
if(head->val == d)
{
temp = head;
head = head->next;
free(temp);
temp = NULL;
}
else
{
temp = head->next;
if(temp != NULL)
{
temp = delete_node(temp,d);
head->next= temp;
}
}
}
return head;
}
/*删除所有val = d的节点*/
List* delete_allnode(List *head, int d)
{
List *temp = head, *cur = head;
if(head != NULL)
{
/*如果第一个就是需要删除的对象*/
if(cur->val == d)
{
temp = cur;
cur = cur->next;
free(temp);
temp = NULL;
temp = delete_allnode(cur, d);
head = temp;
}
else /*不是删除的对象*/
{
cur = head->next;
temp = delete_allnode(cur, d);
/*将得到的链表连接到检测的区域*/
head->next= temp;
}
}
return head;
}
评论