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;//์ ์ผ ๋ ๋
ธ๋๋ฅผ ๊ฐ๋ฆฌํจ๋ค!
}
}