Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given
Given
Given
1->2->3->3->4->4->5
, return 1->2->5
.Given
1->1->1->2->3
, return 2->3
.
因为表头可能被删除, 创建一个dummy node, 令dummynode.next = head, return dummy.next
时间O(n) 空间O(1)
public class Solution { public ListNode deleteDuplicates(ListNode head) { ListNode dummy = new ListNode(0); dummy.next = head; ListNode cur = head; ListNode pre = dummy; while (cur != null && cur.next != null) { if (cur.val == cur.next.val) { int val = cur.val; while (cur != null && cur.val == val) { cur = cur.next; } pre.next = cur; } else { pre = pre.next; cur = cur.next; } } return dummy.next; } }
public class Solution { public ListNode deleteDuplicates(ListNode head) { if (head == null || head.next == null){ return head; } ListNode dummy = new ListNode(0); dummy.next = head; head = dummy; while (head.next != null && head.next.next != null){ if (head.next.val == head.next.next.val){ int val = head.next.val; while (head.next != null && head.next.val == val){ head.next = head.next.next; } } else {//注意一定要在else语句里head往下传递 否则会溢出 head = head.next; } } return dummy.next; } }
没有评论:
发表评论