83、删除链表重复节点

发布时间 2023-10-09 22:46:50作者: MarkLeeBYR

Given a sorted linked list, delete all duplicates such that each element appear onlyonce.

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3

 

public ListNode deleteDuplicates(ListNode head) {
if (head == null || head.next == null)
return head;
ListNode slow = head;
ListNode fast = head.next;
while (slow != null && fast != null) {
if (slow.val != fast.val) {
slow = fast;
fast = fast.next;
} else {
slow.next = fast.next;
fast = fast.next;
}
}
return head;
}