leetcode刷題系列--206. Reverse Linked List 遞歸和非遞歸 c++實現

Reverse a singly linked list.

click to show more hints.

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems

Have you met this question in a real interview? 

Yes
 

下面首先是非遞歸版本,三個指針來做循環,其中一個newhead作爲最後反轉之後的新的頭結點。

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
    ListNode* pre = NULL;
    ListNode* cur = head;
    ListNode* newHead = NULL;
    while(cur)
    {
        ListNode* next = cur -> next;
        if(next   == NULL)
            newHead = cur;
        cur -> next = pre;
        pre = cur;
        cur = next;
    }
    return newHead;
    }
};
下面是遞歸版本,通過遞歸調用,直接進入到最後一個指針元素,此時作爲最新的頭結點,循環跳出來後,head->next的下一個指向head自己 然後head->next賦值爲空,從而完成兩個元素之間的調換。newhead從頭到尾都是沒有變化的,因爲沒人去改變他,所以在遞歸返回的時候,也是可以從頭到尾的返回同一個數值的,這個地方是比較值得借鑑的。
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
     if(head == NULL || head -> next == NULL)
		return head;
	ListNode* newHead = reverseList(head -> next);
	head -> next -> next  = head ;
	head -> next = NULL;
	return newHead;
    }
};

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章