單向鏈表基本操作的遞歸實(shí)現(xiàn)
為了熟悉遞歸的思想,我嘗試了采用遞歸的方式實(shí)現(xiàn)單向鏈表的基本操作。單向的鏈表是C語(yǔ)言課程中接觸到的中比較復(fù)雜的數(shù)據(jù)結(jié)構(gòu),但是他確實(shí)其他數(shù)據(jù)結(jié)構(gòu)的基礎(chǔ),在一般情況下都是采用迭代的形式實(shí)現(xiàn),迭代的形式相比遞歸要節(jié)省時(shí)間和空間,但是代碼相對(duì)來說要復(fù)雜,遞歸往往只是簡(jiǎn)單的幾句代碼,我主要是為了熟悉迭代,并不在性能上進(jìn)行分析。
基本的實(shí)現(xiàn)如下所示:
#include
#include
typedef struct listnode
{
int val;
struct listnode *next;
}List;
/*統(tǒng)計(jì)節(jié)點(diǎn)個(gè)數(shù)*/
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);
}
}
/*刪除一個(gè)節(jié)點(diǎn)的數(shù)據(jù)為d的節(jié)點(diǎn)*/
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的節(jié)點(diǎn)*/
List* delete_allnode(List *head, int d)
{
List *temp = head, *cur = head;
if(head != NULL)
{
/*如果第一個(gè)就是需要?jiǎng)h除的對(duì)象*/
if(cur->val == d)
{
temp = cur;
cur = cur->next;
free(temp);
temp = NULL;
temp = delete_allnode(cur, d);
head = temp;
}
else /*不是刪除的對(duì)象*/
{
cur = head->next;
temp = delete_allnode(cur, d);
/*將得到的鏈表連接到檢測(cè)的區(qū)域*/
head->next= temp;
}
}
return head;
}
評(píng)論