错误代码
class Solution { public: ListNode* ReverseList(ListNode* pHead) { if(pHead == NULL) return NULL; ListNode* p1 = pHead; ListNode* p2 = pHead->next; ListNode* p3 = pHead->next->next; pHead->next = NULL; while(p3 != NULL){ p2->next = p1; p1 = p2; p2 = p3; p3 = p3->next; } p2->next = p1; return p2; } };
此代码会报“段错误:您的程序发生段错误,可能是数组越界,堆栈溢出(比如,递归调用层数太多)等情况引起”
如果链表只有一个节点,那p2就是空指针,p3就是空指针的下一个指针,但空指针是没有next的
正确代码
class Solution { public: ListNode* ReverseList(ListNode* pHead) { if(pHead == NULL) return NULL; else if(pHead->next == NULL) return pHead; ListNode* p1 = pHead; ListNode* p2 = pHead->next; ListNode* p3 = pHead->next->next; pHead->next = NULL; while(p3 != NULL){ p2->next = p1; p1 = p2; p2 = p3; p3 = p3->next; } p2->next = p1; return p2; } };
时间: 2024-10-19 06:13:20