1. 문제 : https://leetcode.com/problems/reverse-linked-list/description/
2. 풀이
Stack에 하나씩 넣어서 역으로 꺼내오면서 next값 역으로 넣어주기
3. 코드
/**
* 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<ListNode> stk = new Stack<>();
ListNode now = head;
ListNode answer;
while(now != null){
stk.add(now);
if(now.next == null) break;
now = now.next;
}
answer = now;
while(!stk.isEmpty()){
now = stk.pop();
if(stk.isEmpty()){
now.next = null;
break;
}
now.next = stk.peek();
}
return answer;
}
}
'💻 Coding Problems Solving > Stack | Queue' 카테고리의 다른 글
[LeetCode] FindKPairsWithSmallestSums (0) | 2023.07.17 |
---|---|
[LeetCode] Kth Largest Element (0) | 2023.07.15 |
[BOJ 1863] 스카이라인 쉬운거 (0) | 2023.06.07 |
[BOJ 11000] 강의실 배정 (0) | 2023.05.25 |
[프로그래머스] LV.2 프린터 (자바 java) (0) | 2023.02.22 |
최근댓글