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.
涉及到改变head node的问题,肯定要用到一个dummy node作为新的头。这道题就是list操作,没有什么难点,只是做list的题时一定要心静,不然很容易把自己搞晕。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode deleteDuplicates(ListNode head) { if(head == null || head.next == null) return head; ListNode newhead = new ListNode(0); newhead.next = head; ListNode slow = newhead; ListNode fast = head; while(slow.next != null){ while(fast.next != null && fast.next.val == slow.next.val){ fast = fast.next; } if(slow.next == fast){ slow = slow.next; fast = fast.next; } else{ slow.next = fast.next; fast = fast.next; } } return newhead.next; } }
Advertisements