1、借助三个临时节点pre,cur,after进行迭代。
class Solution { public: ListNode* ReverseList(ListNode* pHead) { if (pHead == nullptr || pHead->next == nullptr) return pHead; ListNode * pre = nullptr,*cur = pHead,*after = pHead->next; while(cur != nullptr){ cur->next = pre; pre = cur; cur = after; if(after != nullptr) after = after->next; } return pre; } };
2、头插法来做,将元素开辟在栈上,这样会避免内存泄露
ListNode* ReverseList(ListNode* pHead) { // 头插法 if (pHead == nullptr || pHead->next == nullptr) return pHead; ListNode dummyNode = ListNode(0); ListNode* pre = &(dummyNode); pre->next = pHead; ListNode* cur = pHead->next; pHead->next = nullptr; //pre = cur; ListNode* temp = nullptr; while (cur != nullptr) { temp = cur; cur = cur->next; temp->next = pre->next; pre->next = temp; } return dummyNode.next; }
个人更喜欢第二种方法,但是第一种更好理解一点哈