하루의 쉼터

[LeetCode] 206. Reverse Linked List 본문

Coding Test/LeetCode

[LeetCode] 206. Reverse Linked List

Changun An 2020. 12. 6. 22:07
반응형

Question :

Reverse a singly linked list.

Exapmle :

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

Solution.h

#include<iostream>
#include<vector>
#include<stack>
struct ListNode {
    int val;
    ListNode* next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode* next) : val(x), next(next) {}
};

class Solution
{
private: 
    ListNode* result_node;
public :
    ListNode* reverseList(ListNode* head);
    ListNode* inputData(std::vector<int> nums);
    ListNode* reverseStack(ListNode* node);
};

Solution.cpp

#include "Solution.h"

ListNode* Solution::reverseList(ListNode* head)
{
	if (head == nullptr) {
		return head;
	}
	head=reverseStack(head);
	return nullptr;
}

ListNode* Solution::inputData(std::vector<int> nums)
{
	ListNode* list=nullptr;
	ListNode* head=nullptr;
	for (int loop_i = 0; loop_i < nums.size(); loop_i++) {
		if (list == nullptr) {
			list = new ListNode();
			list->val = nums[loop_i];
			head = list;
			list->next = new ListNode();
			list = list->next;
		}
		else {
			if (loop_i < nums.size() - 1) {
				list->val = nums[loop_i];
				list->next = new ListNode();
				list = list->next;
			}
			else if(loop_i==nums.size()-1){
				list->val = nums[loop_i];
				list->next = nullptr;
				return head;
			}
		}

	}

	return head;
}

ListNode* Solution::reverseStack(ListNode* node)
{
	std::stack<int> reverse_stack;
	ListNode* explore = new ListNode();
	ListNode* result = explore;
	while (node != nullptr) {
		reverse_stack.push(node->val);
		node = node->next;
	}
	while (reverse_stack.size() != 0) {
		explore->val = reverse_stack.top();
		reverse_stack.pop();
		if (reverse_stack.size() == 0){
		 	explore->next =nullptr;
		}
		else {
			explore->next = new ListNode();
			explore = explore->next;
		}

	}

	return result;
}

Result

GitHub

github.com/Anchangun/LeetCode/tree/main/Cpp/206.%20Reverse%20Linked%20List

 

Anchangun/LeetCode

문제풀이. Contribute to Anchangun/LeetCode development by creating an account on GitHub.

github.com

 

반응형

'Coding Test > LeetCode' 카테고리의 다른 글

[LeetCode] 9. Palindrome Number  (0) 2021.10.07
[LeetCode] 7. Reverse Integer  (0) 2021.10.05
[LeetCode] 53. Maximum Subarray  (0) 2020.11.30
[LeetCode] 21. Merge Two Sorted Lists  (0) 2020.11.24
[LeetCode] 136. Single Number  (0) 2020.11.23
Comments