-
[java] LeetCode 234. Palindrome Linked List알고리즘 2023. 4. 12. 09:00
문제
https://leetcode.com/problems/palindrome-linked-list/description/
Palindrome Linked List - LeetCode
Can you solve this real interview question? Palindrome Linked List - Given the head of a singly linked list, return true if it is a palindrome or false otherwise. Example 1: [https://assets.leetcode.com/uploads/2021/03/03/pal1linked-list.jpg] Input: hea
leetcode.com
풀이
런너기법을 사용해서 구해보려고 코드를 봤는데... 시간이 많이 걸릴거 같아서..패쓰
우선 덱이나 스택을 학습하려고 푼 문제니 덱,스택을 사용해보자!!
덱
우선 간단하다 덱에 원소를 넣고, 앞과 뒤를 꺼내서 비교만 하면 된다
(ide 테스트용 코드)
package main; import java.util.*; class ListNode { int val; ListNode next; ListNode() {} ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; } } public class Main { //1 23 2 1 public static boolean isPalindrome(ListNode head) { boolean answer = false; Deque<Integer> deque = new ArrayDeque<>(); while(head!=null) { deque.addLast(head.val); head=head.next; } while(!deque.isEmpty()) { int first = deque.pollFirst(); if(deque.size()==0) break; int last = deque.pollLast(); if(first!=last) return false; } return true; } public static void main(String[] args) { ListNode a = new ListNode(); a.val=1; ListNode b = new ListNode(); b.val=2; ListNode c = new ListNode(); c.val=2; ListNode d = new ListNode(); d.val=1; a.next=b; a.next.next=c; a.next.next.next=d; System.out.println(isPalindrome(a)); } }
스택
우선 ListNode의 크기를 구한다. 그리고 원래 ListNode head의 값과 stack에서 pop한 값이 일치하는지 비교한다!
package main; import java.util.*; class ListNode { int val; ListNode next; ListNode() {} ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; } } public class Main { public static boolean isPalindrome(ListNode head) { boolean answer = false; Stack<Integer> st = new Stack<>(); ListNode nh = head; int count=0; while(head!=null){ st.add(head.val); head=head.next; count++; } for(int i=0; i<count/2; i++){ if(st.pop()!=nh.val) return false; nh= nh.next; } return true; } public static void main(String[] args) { ListNode a = new ListNode(); a.val=1; ListNode b = new ListNode(); b.val=2; ListNode c = new ListNode(); c.val=2; ListNode d = new ListNode(); d.val=1; a.next=b; a.next.next=c; a.next.next.next=d; System.out.println(isPalindrome(a)); } }
참조 블로그
'알고리즘' 카테고리의 다른 글
[java] 백준 14888 : 연산자 끼워넣기 (0) 2023.04.18 [java] 백준 18352 : 특정 거리의 도시찾기 (0) 2023.04.17 [java] 1021: 회전하는 큐 (0) 2023.04.11 [java] 백준 1697:숨바꼭질 (0) 2023.04.11 [java] 백준 11724: 연결 요소의 개수 (0) 2023.04.11