LeetCode - 83、删除排序链表中的重复元素
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2
输出: 1->2
示例 2:
输入: 1->1->2->3->3
输出: 1->2->3
1 /** 2 * 列表定义 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */
解法:
1 class Solution { 2 public ListNode deleteDuplicates(ListNode head) { 3 //去掉特殊情况 4 if (head == null || head.next == null) { 5 return head; 6 } 7 8 ListNode prev = head.next; 9 ListNode end = head; 10 11 while(prev != null) { 12 if (end.val == prev.val) { 13 end.next = prev.next; 14 prev = end.next; 15 } else { 16 prev = prev.next; 17 end = end.next; 18 } 19 } 20 21 return head; 22 } 23 }
说明:注意输入的原始列表可能为空,要特殊判断。剩下的就是简单的列表删除操作。
解法优化:只创建一个临时变量
1 public ListNode deleteDuplicates(ListNode head) { 2 ListNode current = head; 3 while (current != null && current.next != null) { 4 if (current.next.val == current.val) { 5 current.next = current.next.next; 6 } else { 7 current = current.next; 8 } 9 } 10 return head; 11 }
解法优化二:去除野指针
1 class Solution { 2 public ListNode deleteDuplicates(ListNode head) { 3 ListNode cur = head; 4 while(cur != null && cur.next != null){ 5 if(cur.val == cur.next.val){ 6 ListNode node = cur.next; 7 cur.next = node.next; 8 node.next = null;//清除野指针 9 }else{ 10 cur = cur.next; 11 } 12 13 } 14 return head; 15 } 16 }
说明(个人理解):ListNode node = cur.next; 中的node的next指针仍指向cur.next.next元素,不会被java的垃圾回收机制回收