Reverse LinkedList

Simply reverse a singly linked list.

Example : Input : 1->2->3->4->5->NULL Output : 5->4->3->2->1->NULL

์•Œ๊ณ ๋ฆฌ์ฆ˜ 1. ์ž„์‹œ ๋ณ€์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด ํ˜„์žฌ ๋…ธ๋“œ์˜ ๋‹ค์Œ ๋…ธ๋“œ๋ฅผ ์ €์žฅํ•œ๋‹ค. 2. ํ˜„์žฌ ๋…ธ๋“œ๊ฐ€ ์ด ์ž„์‹œ๋ณ€์ˆ˜๋ฅผ ํ†ตํ•ด ๋‹ค์Œ ๋…ธ๋“œ๋กœ ์ด๋™ํ•œ๋‹ค. ํ˜„์žฌ ๋…ธ๋“œ๋Š” prev๊ฐ€ ๋œ๋‹ค. 3. 1~2๋ฅผ ๊ฑฐ์น˜๋ฉฐ ํ˜„์žฌ ๋…ธ๋“œ์˜ ๋‹ค์Œ ๋…ธ๋“œ๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋Š” ํฌ์ธํ„ฐ๋Š” prev๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋„๋ก ํ•œ๋‹ค.

/**
 * 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 curr = head;
        ListNode prev = null;
        
        while(curr != null) {
            ListNode nextTemp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = nextTemp;
        }
        return prev;//์ œ์ผ ๋ ๋…ธ๋“œ๋ฅผ ๊ฐ€๋ฆฌํ‚จ๋‹ค!
        
    }
}

Last updated