链表中节点的计数及链表的反转
1.链表中节点的计数
int getnum(node * phead)
{
for(int i = 0; phead != NULL; i++,phead = phead->pNext)
{
}
}这是一种装逼语句,有一个弊端就是执行完成之后,i 就不存在了。
最好还是这么写
int getnum(node *phead)
{
int i = 1;
for(; phead != NULL; phead = phead->pNext)
{
i++;
}
}
用递归怎么写
int getnum(node *phead)
{
if(phead==NULL)
{
return 0;
}
else
{
return 1 + getnum(phead->pNext)
}
}
2.链表的反转
node *rev(node *phead)
{
if (phead==NULL || phead->pNext==NULL)
{
return NULL;
}
else
{
node *pre, *pcur, *pnext;//三个节点
pre = pcur = pnext = NULL;//赋值表达式
pre = phead;
pcur = phead->pNext;
while (pcur) //pcur!=null
{
pnext = pcur->pNext;//保存下一个节点
pcur->pNext = pre;//前一个节点
pre = pcur;
pcur = pnext;//轮替
}
phead->pNext = NULL;
phead = pre;//保存节点
return phead;
}
}
用递归的方式
node *fanzhuan(node * phead)
{
if(phead==NULL || phead->pNext==NULL)
{
return phead;
}
else
{
node *pnext = phead->pNext;
node *head = fanzhuan(pnext);
pnext->pNext = phead;
phead->pNext = NULL;
return head;
}