LeetCode 83. Remove Duplicates from Sorted List
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; }
LeetCode给出的答案在判断空指针的操作上更简洁
public ListNode deleteDuplicates(ListNode head){ ListNode cur = head; //如果head=null,则程序就不会执行后半句cur.next != null,因此不存在在head=null的前提下,取head.next的情况 while(cur != null && cur.next != null){ if(cur.val == cur.next.val){ cur.next = cur.next.next; } else{ cur = cur.next; } } return head; }