原题链接在这里:https://leetcode.com/problems/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
.
题解:
Time Complexity: O(n), n是list长度. Space: O(1).
AC Java:
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode deleteDuplicates(ListNode head) { 11 if(head == null || head.next == null){ 12 return head; 13 } 14 ListNode cur = head; 15 while(cur.next != null){ 16 if(cur.val == cur.next.val){ 17 cur.next = cur.next.next; 18 }else{ 19 cur = cur.next; 20 } 21 } 22 return head; 23 } 24 }
跟上Remove Duplicates from Sorted List II, Remove Duplicates from Sorted Array.