Skip to content

Commit 21c6a70

Browse files
author
jinvicky
committed
reverse-linked-list solution, 반복문 포인터와 재귀 케이스를 추가
1 parent 4fab8ab commit 21c6a70

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

reverse-linked-list/jinvicky.java

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,4 +24,40 @@ public ListNode reverseList(ListNode head) {
2424
current.next = null; // 마지막 tail 정리
2525
return newHead;
2626
}
27+
28+
/**
29+
* 포인터 반복문을 새로 배웠을 때 fast/slow와 같은 투 포인터 알고리즘과 헷갈렸지만 둘은 전혀 다르다.
30+
* 포인터 반복문
31+
* * 링크 방향 뒤집기
32+
* * 3개 포인터 (prev, cur, next)
33+
* * 리스트 자체 구조 변경
34+
* <p>
35+
* 투 포인터
36+
* * 중간, 사이클, 교차점 등 탐색
37+
* * 2개 포인터 (slow, fast)
38+
* * 리스트 구조 그대로, 위치 정보만 얻음
39+
* <p>
40+
* https://bcp0109.tistory.com/142
41+
*/
42+
public ListNode reverseListByPointer(ListNode head) {
43+
ListNode prev = null;
44+
ListNode cur = head;
45+
while (cur != null) {
46+
ListNode next = cur.next; // next라는 temp 변수를 사용해서 prev와 cur.next 값을 바꾼다.
47+
cur.next = prev;
48+
prev = cur;
49+
cur = next;
50+
// 대각선으로 / / / / 으로 변수명 암기하기
51+
}
52+
return prev;
53+
}
54+
55+
public ListNode reverseListByRecursion(ListNode head) {
56+
// head.next가 null인지도 확인하는 로직이 필요합니다. (nullPointerException 방지)
57+
if (head == null || head.next == null) return null;
58+
ListNode newHead = reverseListByRecursion(head.next);
59+
head.next.next = head;
60+
head.next = null;
61+
return newHead;
62+
}
2763
}

0 commit comments

Comments
 (0)