单向链表的反转(或者叫逆置)是经常被问到的考题。建议考前临阵磨枪,强背一波。
代码说明:
void reverse_list(node_t *head)
此函数实现带头结点(也叫表头、哑结点)的单链表的反转。
head
是头结点的地址。
示意图如下:
|head |—>| 1st node|—>|2nd node|—>|… |—>NULL
struct node
{
int data;
struct node *next;
};
typedef struct node node_t;
void reverse_list(node_t *head)
{
if((head->next==NULL) || (head->next->next==NULL))
return;
node_t *p1;
node_t *p2;
node_t *p3;
p1 = head->next;
p2 = p1->next;
while(p2)
{
p3 = p2->next;
p2->next = p1;
p1 = p2;
p2 = p3;
}
head->next->next = NULL;
head->next = p1;
}
测试代码略。