Skip to content

Instantly share code, notes, and snippets.

@superlayone
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save superlayone/a737af95fefc29232b26 to your computer and use it in GitHub Desktop.
Save superlayone/a737af95fefc29232b26 to your computer and use it in GitHub Desktop.
Reverse list

###Reverse list

反转list,使用递归方式

如图所示,h为已经经过递归反转过的链表头,在递归之前保存的q指针已经是反转之后的尾指针,修改p指针为新的尾节点,返回h节点

###Code

    struct ListNode
    {
    	int val;
    	ListNode* next;
    	ListNode(int v):val(v),next(nullptr){}
    };
    
    ListNode* reverseListRecur(ListNode* head)
    {
    	if(head == nullptr)
    	{
    		return head;
    	}
    	ListNode* p = head;
    	ListNode* q = head->next;
    	if(q == nullptr)
    	{
    		return head;
    	}
    	ListNode* newHead = reverseListRecur(p->next);
    
    	q->next = p;
    	p->next = nullptr;
    
    	return newHead;
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment