83 Remove Duplicates from Sorted List
1. Question
Given a sorted linked list, delete all duplicates such that each element appear onlyonce.
For example,
Given1->1->2
, return1->2
.
Given1->1->2->3->3
, return1->2->3
.
2. Implementation
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null) {
return head;
}
ListNode preNode = head, curNode = head.next;
while (curNode != null) {
if (preNode.val == curNode.val) {
preNode.next = curNode.next;
}
else {
preNode = preNode.next;
}
curNode = curNode.next;
}
return head;
}
}
3. Time & Space Complexity
时间复杂度O(n), 空间复杂度O(1)
Last updated
Was this helpful?