leetcode 206.反转链表
两种思路,用递归或者迭代实现。理论性能差不多。虽然递归会比迭代多很多的函数调用栈开销。。
递归代码如下(能够使用递归法的两要素,出口,以及子问题是相同解法的更简单问题)
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { if(head==NULL||head->next==NULL)return head; ListNode* pre=head->next; ListNode* ans=reverseList(pre); pre->next=head; head->next=NULL; return ans; } };
迭代代码如下(注意temp变量的使用)
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { if(head==NULL||head->next==NULL)return head; ListNode* curNode=head->next; ListNode* preNode=head; ListNode* temp; while(curNode!=NULL){ temp=curNode->next; curNode->next=preNode; preNode=curNode; curNode=temp; } head->next=NULL; return preNode; } };