给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2
输出: 1->2
示例 2:
输入: 1->1->2->3->3
输出: 1->2->3
思路:
(1)定义两个指针,cur1和cur2,初始时cur1指向head,cur2指向head.next
(2)如果俩指针的值相等,就让cur1的next等于cur2的next,同时cur2指向next
(3)如果俩指针不相等,cur1指向next,cur指向next
(4)然后继续比较cur2和cur1的值
代码如下:
public class LeetCode83 { public static class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } public ListNode deleteDuplicates(ListNode head) { if (head == null || head.next == null) { return head; } ListNode prev = head; ListNode cur = head.next; while (cur != null) { if (prev.val == cur.val) { prev.next = cur.next; } else { prev = prev.next; } cur = cur.next; } return head; } }