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;
    }
};

你可能感兴趣的:(leetcode刷题C++)