题解 | #反转链表#
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
ListNode* ReverseList(ListNode* head) { // write code here if(head == NULL) return NULL; ListNode* cur = head; ListNode* pre = NULL; while(cur != NULL){ ListNode* temp = cur->next; cur->next = pre; pre = cur; cur = temp; } return pre; } 递归 ListNode* ReverseList(ListNode* head) { if(head == NULL || head -> next == NULL) return head; ListNode* newHead = ReverseList(head->next); // 假如有ABCD head = a // B->next = A 相当于B指向了A head->next->next = head; // 再将A->next 指向null head->next = NULL; return newHead; }