Remove Duplicates from Sorted List
Input: 1->1->2
Output: 1->2Input: 1->1->2->3->3
Output: 1->2->3Solution
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode p, q;
p = head;
q = head;
while (q != null) {
if (q.val != p.val) {
p.next = q;
p = p.next;
}
q = q.next;
}
if (p != null) {
p.next = null;
}
return head;
}
}Last updated