[LeetCode#83]Remove Duplicates from Sorted List
5642 단어 LeetCode
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,Given
1->1->2 , return 1->2 .Given 1->1->2->3->3 , return 1->2->3 . My analysis:
When sovling linkedlist problems, two boundary cases needed to be very carefully treated, otherwise it may result in head lossing or get null pointer exception.
1. the head node might be changed.
Thus we may lose the information for new result linked list. One classic way is to use a dummy node to always pointer the the head the list.
In this problem, when duplicates appear, we would keep one copy. Thus the head node could never be changed, we won't need to set a dummy head for this case.
2. If we have a scaner over the linkedlist, or several scanner(which we only need to consider the faster scanner).
The usually checking condition when traversaling the list is "while (faster != null)", In this case, we could only guarantee at the moment of entering the while loop, the faster is not null pointer. However, we may move the faster in the while loop:
like:
while (faster != null && ptr1.val == faster.val) {
faster = faster.next;
}
the faster may reach the end of the list, thus faster is null.
if we have a statement: "fast = faster.next" without any checking, it would result in a null pointer exception.
???if we add a checking over here, it seems to distort the logic !
In fact, the boundary case is the ending procedure over the list, after it, the invariant is over, we would not need to care about that!!! My first solution:
if (head == null)
return null;
ListNode ptr1 = head;
ListNode ptr2 = head.next;
while (ptr2 != null) {
while (ptr2 != null && ptr1.val == ptr2.val) {
ptr2 = ptr2.next;
}
ptr1.next = ptr2;
ptr1 = ptr2;
if (ptr2 != null) //may directly reach the end
ptr2 = ptr2.next;
}
return head; My elegant solution:
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null)
return null;
ListNode dummy = new ListNode(0);
ListNode pre = dummy;
ListNode cur = head;
while (cur != null) {
if (pre == dummy || pre.val != cur.val) {
pre.next = cur;
pre = cur;
}
cur = cur.next;
}
pre.next = null; //remember the last step!!!
return dummy.next;
}
} 이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
python 문자열 입력으로 모든 유효한 IP 주소 생성(LeetCode 93번 문제)이 문제의 공식 난이도는 Medium으로 좋아요 1296, 반대 505, 통과율 35.4%를 눌렀다.각 항목의 지표로 말하자면 보기에는 약간 규범에 맞는 것 같지만, 실제로도 확실히 그렇다.이 문제의 해법과 의도는 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.