题解 | #反转链表# 尾指针头插法解决带值头节点型链表反转
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return ListNode类 */ struct ListNode* ReverseList(struct ListNode* head ) { // write code here if(head==NULL) // 判空 return head; struct ListNode* p = head; // 建立指针p while(p->next) // 找到链表最后一个节点作为头结点 { p=p->next; } struct ListNode* q; while(head!=p) // 以p为头节点使用头插法重建链表 { q=head; // 待插入节点 head=head->next; // 移动原头指针 q->next=p->next; // 插入到p后 p->next=q; } return head; }