[LeetCode] Reverse Linked List

nRecode·2021년 3월 9일
0

Algorithm

목록 보기
42/48

문제

Given the head of a singly linked list, reverse the list, and return the reversed list.

입출력 예

Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]

접근

입력으로 들어오는 head의 next를 순회하면서 진행합니다. 먼저 head의 next를 다른 변수에 담아 두고 head의 next를 null로 변경합니다. 입출력의 예시와 같다면 head는 [1] nextNode는 [2,3,4,5]가 될 것 입니다. 이때 while문을 사용하는데 nextNode가 존재한다면을 조건으로 갖습니다. 그 이유는 nextnode를 통해 head를 reverse 값으로 변경하기 위함입니다.

while문 안에서의 로직은 다음과 같습니다. 선언했던 nextNode의 next를 새로운 변수 nextNextNode에 선언하고 nextNode의 next를 head로 변경합니다. 다음 head를 변경된 nextNode로 할당하고 nexNode는 nextNextNode로 할당합니다. 무슨 말인지 모르겠습니다... 코드를 봅니다.

풀이

var reverseList = function(head) {
    console.log(head)
    if (!head) return head;
    
	let nextNode = head.next;
	
	// 맨 마지막 노드는 항상 null이 되도록!
	head.next = null;
    
	// head에 next가 있는 동안 아래의 while문을 돌린다 
	while (nextNode) {
	    const nextNextNode = nextNode.next; // nextNode의 그 다음 노드를 변수 nextNextNode로 지정해준다
		nextNode.next = head; // nextNode.next는 제일 처음에 있던 head node로 대체 시켜준다
	    head = nextNode; // 기존의 head node는 그 뒤에 있던 nextNode로 대체 시켜준다
	    nextNode = nextNextNode; // 기존의 next node는 그 뒤에 있던 nextNextNode로 대체 시켜준다
	    // 이 cycle 이 반복되면서 기존의 순서는 반대로 뒤바뀔 것이다.
	}

    return head;
};
profile
안정성, 확장성 있는 서버를 구축하고 가꾸는 개발자를 목표로 공부하고 있습니다. 🤔🤔🤔🤔 부족하기에 맞지 않는 내용이 있을 수 있습니다. 가감없이 피드백 해주시면 정말 감사하겠습니다..🙏

0개의 댓글