给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
示例 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:
输入:head = [1,2]
输出:[2,1]
示例 3:
输入:head = []
输出:[]
提示:
- 链表中节点的数目范围是 [0, 5000]
- -5000 <= Node.val <= 5000
解答思路:
- 链表的头插法
struct ListNode* reverseList(struct ListNode* head){
if (head==NULL || head->next==NULL){
return head;
}
struct ListNode *pre = NULL; //pre指向空节点
struct ListNode *cur = head; //cur指向头结点head
struct ListNode *next = head->next; //在断开链之前,暂存后继节点
while (next!=NULL){ // 如果head为空就不会进入循环
cur->next = pre; //断开现在的链,重新指向
pre = cur; //pre 暂存 cur,作为cur下一步的前继节点
cur = next; //cur 访问下一节点
next = next->next;
}
cur->next = pre; //此时cur指向null,返回cur的前继节点pre
return cur;
}