面试算法题. 单链表反转的递归版本

// 链表节点结构
struct ListNode {
	ListNode(int a = 0) : val(a), 
			next(nullptr) {
	}

	int val;
	ListNode* next;
};


// 递归版本的链表反转
ListNode* ReverseList(ListNode* head) {

	if (nullptr == head)
		return nullptr;

	if (nullptr == head->next)
		return head;

	ListNode* newHead = ReverseList(head->next);
	head->next->next = head;
    head->next = nullptr;

	return newHead;
}

int main(int argc, char* argv[]) {


	ListNode* head = new ListNode(1);
	head->next = new ListNode(2);
	head->next->next = new ListNode(3);
	head->next->next->next = new ListNode(4);

	ListNode *newHead = ReverseList(head);

	return 0;
}

猜你喜欢

转载自blog.csdn.net/paradox_1_0/article/details/106294420