LeetCode 03: Remove Duplicates From Sorted List

Daisy·2022년 12월 22일

Leetcode

목록 보기
3/7

문제링크: https://leetcode.com/problems/remove-duplicates-from-sorted-list/

Problem

정렬이 되어서 주어진 Sorted Linked List에서 중복된 값을 제거한 Linked List를 구하는 간단한 문제이다.

Solution

Linked List에서 노드를 remove하는 방법을 안다면 쉽게 풀 수 있는 문제이다.

현재 노드와 연결된 다음 노드를 지울 때, node.next의 값을 다다음 노드인 node.next.next 값으로 바꿔주면 된다.

node.next = node.next.next

이미 리스트가 정렬되어 있기 때문에, 현재 노드와 다음 노드의 값이 동일할 때 다음 노드를 지워주는 방식으로 문제를 해결하면 끝이다.

current = head

while (current!= None and current.next != None):
	if current.val == current.next.val:
		current.next = current.next.next
	else: 
		current = current.next

return head

0개의 댓글