挑战面试编程:链表逆转的多种实现
链表的逆转是一种常见又较复杂的操作,下面使用多种方式进行实现:while、递归以及goto。
代码:
#include <stdio.h>
#include <stdlib.h>
//链表节点
typedef struct node
{
int data;
struct node *next;
}Node;
//逆转的while实现
void rev(Node **list) //链表逆转
{
if (*list == NULL || (*list)->next == NULL) //空或者只有一个节点
{
return;
}
else
{
Node *pPre, *pCur, *pNext;
pPre = *list;
pCur = (*list)->next;
while (pCur)
{
pNext = pCur->next;
pCur->next = pPre;
pPre = pCur;
pCur = pNext;
}
(*list)->next = NULL;
*list = pPre;
}
}
//逆转的递归实现
void rev_r(Node **list, Node *pCur, Node *pNext)
{
if (pCur == NULL || pNext == NULL)
{