Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
题意:给定一个已经排好序的链表,删除链表中的重复元素
思路;利用pre指向前一个结点,cur指向当前结点,判断两个结点值是否相等。
public ListNode deleteDuplicates(ListNode head) { //要先判断head是否为null,如果在head为null的情况下执行cur = head.next,则相当于对空指针进行操作,会报空指针异常 if (head == null) return head; ListNode pre = head; ListNode cur = head.next; while (cur != null) { if (pre.val == cur.val) { pre.next = cur.next; } else { pre = pre.next; } cur = cur.next; } return head; }