83、删除链表重复节点

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;
}
posted @ 2023-10-09 22:42  MarkLeeBYR  阅读(2)  评论(0编辑  收藏  举报