# 剑指offer之反转链表

## 3 代码实现

#include <stdio.h>

typedef struct Node
{
int val;
struct Node *next;
} Node;

/*
*print list
*/
{
if (head == NULL)
{
return;
}
Node *p = head;
while (p != NULL)
{
printf("value is %d\n", p->val);
p = p->next;
}
}

/*
*reverse list
*/
struct Node* reverse(Node *head)
{
if (head == NULL)
{
printf("reverse head is NULL\n");
return NULL;
}
Node *end = NULL;
Node *p = head;
Node *start = NULL;
while (p != NULL)
{
//next node
Node *next = p->next;
//If next is NULL, we will store p, we will return p in the end;
if (next == NULL)
{
end = p;
}
p->next = start;
start = p;
p = next;
}
return end;
}

int main()
{
//0->1->2->3;
Node head, node1, node2, node3;
node1.val = 1;
node1.next = &node2;
node2.val = 2;
node2.next = &node3;
node3.val = 3;
node3.next = NULL;
printf("list will reverse\n");
Node *hello = reverse(&head);
print_list(hello);

return 0;
}

## 4 运行结果

value is 0
value is 1
value is 2
value is 3
list will reverse
value is 3
value is 2
value is 1
value is 0