코딩테스트

206. Reverse Linked List

nayoon 2024. 2. 4. 17:58

recursive way

 

 

iterative way

내 풀이

/**
 * 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) {
        if (head == null) {
            return head;
        }

        List<Integer> nums = new ArrayList<>();
        while(head != null) {
            nums.add(head.val);
            head = head.next;
        }

        Collections.reverse(nums);

        ListNode nHead = new ListNode();
        ListNode node = new ListNode();
        nHead.next = node;

        for(int i = 0; i < nums.size() - 1; i++) {
            node.val = nums.get(i);
            node.next = new ListNode();
            node = node.next;
        }

        node.val = nums.get(nums.size() - 1);
        
        return nHead.next;
    }
}

 

참고해서 고친 풀이

/**
 * 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) {
        ListNode prev = null;
        ListNode curr = head;
        
        while(curr != null) {
            ListNode temp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = temp;
        }
        
        return prev;
    }
}

 

'코딩테스트' 카테고리의 다른 글

876. Middle of the Linked List  (0) 2024.02.05
217. Contains Duplicate  (0) 2024.02.05
141. Linked List Cycle  (0) 2024.01.29
21. Merge Two Sorted Lists  (0) 2024.01.29
235. Lowest Common Ancestor of a Binary Search Tree  (0) 2024.01.28