Given the head of a singly linked list, return true if it is a palindrome.

https://leetcode.com/problems/palindrome-linked-list/

 

Palindrome Linked List - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

다시 합창합시다~를 거꾸로하면 다시 합창합시다~ 이런 LinkedList를 구하는 문제이다. 전 포스팅에서 다룬 ReverseLinkedList를 이용해서 코드를 작성했었으나. . . . 안됐다. 왜????

public boolean isPalindrome(ListNode head) {
        ListNode reverseHead = reverseList(head);
        
        ListNode p1 = head;
        ListNode p2 = reverseHead;
        
        while(head != null) {          
            if(head.val != reverseHead.val)  return false;     
            
            head = head.next;
            reverseHead = reverseHead.next;
        }
        
        return true;
    }
    
    public ListNode reverseList(ListNode head) {
        if (head == null) {
            return head;
        }
        ListNode dummy = new ListNode(0);
        dummy.next = null;
     
        while(head != null) {
            ListNode newNode = new ListNode(head.val);
            newNode.next = dummy.next;
            dummy.next = newNode;
            head = head.next;
        }
        return dummy.next;
        
        
    }

참고 코드

 

이 분과 내가 구현하고자 하는 코드가 비슷해서 참고했는데 왜 내가 작성한 reverse화 하는 코드는 안되고 이것은 되는가 좀 더 고민해봐야겠다.

참고로 내가 작성한 코드 또한 참고 코드이다. (전 포스팅 206번에도 언급)

// 이것과
public ListNode reverseList(ListNode head) {
        ListNode prev = null;
        
        
        if (head == null) {
            return head;
        }
        while(head != null) {
            ListNode cur = head;
            head = head.next;
            cur.next = prev;
            prev = cur;
            
        }
        return prev;
        
        
    }
    
 // 이것의 차이
 
 public ListNode reverseList(ListNode head) {
        if (head == null) {
            return head;
        }
        ListNode dummy = new ListNode(0);
        dummy.next = null;
     
        while(head != null) {
            ListNode newNode = new ListNode(head.val);
            newNode.next = dummy.next;
            dummy.next = newNode;
            head = head.next;
        }
        return dummy.next;
       
    }

 

+ Recent posts