leetcode linked list

이기현·2020년 8월 3일

코딩테스트 준비

목록 보기
8/20

간단한 문제였는데, linked list의 개념이 헷갈려서 조금 시간이 걸렸던 문제이다.
linkedlist문제를 풀 때에는 pre, current, next의 값을 잘 저장하고 변경해주는 것이 중요하다.

Reverse Linked List

/**
 * 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 pre = null;
        ListNode curr = head;
        ListNode next = null;
         while(curr!= null){
            next = curr.next;
            curr.next = pre;
            pre = curr;
            curr = next;
         }
        head = pre;
        //System.out.println(head.val);
        return head;
    }
    
}
profile
실력을 쌓아가는 하루하루

0개의 댓글