ID | Title | Difficulty | |
---|---|---|---|
Loading... |
83. Remove Duplicates from Sorted List
Easy
LeetCode
Linked List
Problem
Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2
Output: 1->2
Example 2:
Input: 1->1->2->3->3
Output: 1->2->3
Code
/**
* 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 || head.next == null) return head;
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode curr = dummy;
while(curr.next != null){
int val = curr.next.val;
while(curr.next.next != null && curr.next.next.val == val){
curr.next = curr.next.next;
}
curr = curr.next;
}
return dummy.next;
}
}
按 <- 键看上一题!
82. Remove Duplicates from Sorted List II
按 -> 键看下一题!
84. Largest Rectangle in Histogram