题目链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/
题目如下:
/**
* 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||head.next==null) return head;
//比较是否存在两个数相同,故需两个指针,一个pre一个cur
ListNode pre=head,cur=head.next;
while(cur.next!=null){
if(pre.val==cur.val){
pre.next=cur.next;
cur=cur.next;
}else{
pre=cur;
cur=cur.next;
}
}
if(pre.val==cur.val) pre.next=null;
return head;
}
}