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
.
public ListNode deleteDuplicates(ListNode head) { if (head == null || head.next == null) { return head; } ListNode temp = head; while (temp.next != null) { if (temp.next.val == temp.val) { temp.next = temp.next.next; } else { temp = temp.next; } } return head; }
Remove Duplicates from Sorted List II:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5
, return 1->2->5
.
Given 1->1->1->2->3
, return 2->3
.
算法分析:区别问题1,这个是把所有重复元素都删掉,一个不留,所有要用两重while去重,上面一题去重时只需要一重循环。
public ListNode deleteDuplicates2(ListNode head) { if(head == null || head.next == null) { return head; } ListNode pre = new ListNode(0);//记录头结点,因为开头如果有重复元素,head将改变 pre.next = head; ListNode temp = pre; while (temp.next != null && temp.next.next != null) { if(temp.next.val == temp.next.next.val) { int dup = temp.next.val; while(temp.next != null && temp.next.val == dup)//去掉所有重复元素 { temp.next = temp.next.next; } } else { temp = temp.next; } } return pre.next; }
时间: 2024-10-23 07:37:56