反转链表
输入一个链表,反转链表后,输出链表的所有元素。
我的代码:
class Solution { public: ListNode* ReverseList(ListNode* pHead) { if(pHead == NULL) return NULL; stack<ListNode*> sta; while(pHead != NULL) { sta.push(pHead); pHead = pHead->next; } ListNode* p = sta.top(); ListNode* pp = sta.top(); while(!sta.empty()) { p = sta.top(); sta.pop(); if(!sta.empty()) p->next = sta.top(); else p->next = NULL; } return pp; } };
小黑的代码:
class Solution { public: ListNode* ReverseList(ListNode* pHead) { if(pHead == NULL) return NULL; stack<ListNode*> sta; while(pHead != NULL) { sta.push(pHead); pHead = pHead->next; } ListNode* p = sta.top(); ListNode* pp = sta.top();//记录链表的头 sta.pop(); while(!sta.empty()) { p->next = sta.top(); sta.pop(); p=p->next; } p -> next = NULL; return pp; } };
3个指针代码:
Node* Reverse(Node* node) { Node* pre = node; Node* p = node->next; Node* pnxt = p->next; node->next = NULL; while(pnxt != NULL) { p->next = pre; pre = p; p = pnxt; pnxt = pnxt->next; } p->next = pre; return p; }
改进版:
Node* Reverse(Node* node) { Node* pre = NULL;//被指向的 Node* p = node;//当前 Node* pnxt = node->next;//要断开的 while(pnxt != NULL) { p->next = pre; pre = p; p = pnxt; pnxt = pnxt->next; } p->next = pre; return p; }