图解反转单向链表
核心代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *pNext;
* };
*//* 反转函数,输入待反转链表头,返回反转后的链表头 */
struct ListNode* reverseList(struct ListNode* head){
struct ListNode *pre = NULL;
struct ListNode *next = NULL;
while (head) {
next = head->pNext;
head->pNext= pre;
pre = head;
head = next;
}
return pre;
}
1,存在链表:
2,定义两个辅助指针
3,进入第1次while循环(反转第1个节点)
4,进入第2次while循环(反转第2个节点)
5,进入第3次while循环(反转第3节点)
6,进入第4次while循环(反转第4节点,结束)