LeetCode 反转链表(递归 / 迭代)

	//递归
	//reverseList()返回的是从currentNode节点开始后面的链表整个反转后的结果的头节点
	ListNode * reverseList(ListNode* currentNode) {
		if (currentNode == nullptr)return nullptr;

		if (currentNode->next == nullptr)return currentNode;
		//未到头
		if (currentNode->next->next != nullptr) {
			//反转链表的头节点
			ListNode* headNode = reverseList(currentNode->next);
			//当前节点的下个节点进行反转
			currentNode->next->next = currentNode;
			currentNode->next = nullptr;
			return headNode;
		}
		//到头
		else {
			//当前节点的下个节点为反转链表的头节点,再进行反转
			currentNode->next->next = currentNode;
			ListNode* headNode = currentNode->next;
			currentNode->next = nullptr;
			return headNode;
		}
	}
	//迭代
	//三个指针遍历一遍进行反转
	ListNode * reverseList(ListNode* head) {
		if (head == nullptr)return nullptr;
		if (head->next == nullptr)return head;
		ListNode* currentNode, *middleNode, *nextNode;
		currentNode = nullptr;
		middleNode = head;
		nextNode = middleNode->next;
		while (middleNode != nullptr)
		{
			middleNode->next = currentNode;
			currentNode = middleNode;
			middleNode = nextNode;
			if (nextNode != nullptr)nextNode = nextNode->next;
		}
		return currentNode;
	}

你可能感兴趣的:(LeetCode,链表)