struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };
方法1: 迭代
class Solution { public: ListNode* ReverseList(ListNode* pHead) { ListNode *pre; ListNode *next; ListNode *curr; curr=pHead; pre=NULL; while(curr!=NULL) { next=curr->next; //保存下一个 curr->next=pre; //指向前面一个 pre=curr; //保存前面一个 curr=next; //移动到下一个 } return pre; } };
方法2:递归
class Solution { public: ListNode* ReverseList(ListNode* pHead) { if(pHead==NULL || pHead->next==NULL) return pHead; ListNode *new_head = ReverseList(pHead->next); pHead->next->next=pHead; pHead->next=NULL; return new_head; } };
原文:https://www.cnblogs.com/520dada/p/14828268.html