LeetCode 206. Reverse Linked List
经典问题,可以用迭代或是递归来做。迭代也有多种思路,一定要注意各种边界条件。
解法一:直接反转,顾名思义,要记录前面的结点信息,才能反转。能背下来最好。
class Solution { public: ListNode* reverseList(ListNode* head) { ListNode *prev=NULL, *curr=head; while (curr!=NULL){ ListNode *nextNode=curr->next; curr->next = prev; prev = curr; curr = nextNode; } return prev; } };
解法二:把后面的结点依次放到最前面。first指针始终指向初始第一个节点,后面的节点依次挪到最前面。
class Solution { public: ListNode* reverseList(ListNode* head) { if (head==NULL) return NULL; ListNode *dummy=new ListNode(0); dummy->next = head; ListNode *first=head; while (first->next!=NULL){ ListNode *nextNode=first->next; first->next = nextNode->next; nextNode->next = dummy->next; dummy->next = nextNode; } return dummy->next; } };
解法三:递归。可以画图帮助思考,尤其是 head->next->next = head; 这一句。注意一定要把 head->next 置于 NULL,否则链表内会有环产生。
class Solution { public: 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; } };

浙公网安备 33010602011771号