나는 한 번 순회해서 n을 구하고, n /2 값을 구한 다음 next
를 바꿔줄 노드를 선택하도록 했다.
찾은 노드의 next = next.next
로 바꿔주면 된다고 생각했다.
노드가 하나인 경우는 그냥 삭제하고 리턴하면 된다.
class Solution {
public ListNode deleteMiddle(ListNode head) {
if (head.next == null) {
return null;
}
ListNode nextNode = head.next;
int n = 1;
while (nextNode != null) {
nextNode = nextNode.next;
n++;
}
nextNode = head;
int targetIndex = n / 2;
for (int i=0; i<targetIndex-1; i++) {
nextNode = nextNode.next;
}
nextNode.next = nextNode.next.next;
return head;
}
}
근데 참고하려고 솔루션을 보니 slow / fast 두 개의 포인터를 주고 하는 방식이 있구나
slow는 next, fast는 next.next로 증가하게 두고 && 조건으로 둘 다 만족하지 못할 때 탈출하면 딱 중간에 있는 노드를 찾을 수 있게 된다.
GPT한테도 물어봤는데 처음 대답하는 것은 아래 방식이였다.
그래서 내 접근 방식 검증 차 두 개의 포인터를 사용하지 않는 방법을 물었더니 내가 작성한 코드랑 똑같은게 나왔다.
class Solution {
public ListNode deleteMiddle(ListNode head) {
if (head == null || head.next == null) {
return null; // 노드가 하나뿐이면 삭제 후 null 반환
}
ListNode slow = head, fast = head;
ListNode prev = null; // 중간 노드의 이전 노드를 저장
while (fast != null && fast.next != null) {
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
// 중간 노드를 삭제
prev.next = slow.next;
return head;
}
}