迭代法
ListNode* ReverseList(ListNode* pHead) { // 判断链表为空或长度为1的情况 if(!pHead || pHead->next == NULL){ return pHead; } ListNode *pre = NULL; // 当前节点的前一个节点 ListNode *next = NULL; // 当前节点的下一个节点 while(pHead){ next = pHead->next; // 记录当前节点的下一个节点位置; pHead->next = pre; // 让当前节点指向前一个节点位置,完成反转 pre = pHead; // pre 往右走 pHead = next;// 当前节点往右继续走 } return pre; }
递归法
ListNode* reverseList(ListNode* head) {
if (head == NULL || head->next == NULL) return head;
ListNode* p = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return p;
}