Remove Duplicates from Sorted List删除排序链表中的重复元素
Given the head
of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次
输入: 1->1->2
输出: 1->2
输入: 1->1->2->3->3
输出: 1->2->3
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head==null){
return null;
}
ListNode p = head;
while(p.next!=null){
if (p.val == p.next.val){
p.next = p.next.next;
}
else{
p = p.next;
}
}
return head;
}
}