코린이의 소소한 공부노트

[LeetCode/Easy] 206. Reverse Linked List 본문

코딩테스트 풀이/JAVA

[LeetCode/Easy] 206. Reverse Linked List

무지맘 2023. 5. 15. 23:39

1. Input

1) ListNode head

 

2. Output

1) 연결 리스트를 뒤집은 결과를 반환

 

3. Constraint

1) 노드의 수의 범위는 [0, 5000]이다.

2) -5000 <= Node.val <= 5000

 

4. Example

Input: head = [1,2,3,4,5] -> Output: [5,4,3,2,1]

 

5. Code

1) 첫 코드(2023/05/15)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        Stack<Integer> stack = new Stack<>();
        while(head!=null){
            stack.push(head.val);
            head = head.next;
        }
        ListNode ans = stack.empty() ? null : new ListNode(stack.pop());
        ListNode cur = ans;
        while(!stack.empty()){
            cur.next = new ListNode(stack.pop());
            cur = cur.next;
        }
        return ans;
    }
}