83. 删除排序链表中的重复元素

双指针法:
定义两个指针temp和cur,开始时,temp指向head,cur指向head.next。遍历链表,如果temp.val = cur.val,temp指向cur的下个节点,cur指针往后移一个节点,这时cur指向的节点为新节点,因此temp指针无需移动,如果temp.val != cur.val,temp和cur都各往后移动一个节点,知道遍历完链表。


class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode temp = head,cur = head;

        while(cur != null){
            if(temp.val == cur.val){
                temp.next = cur.next;
                cur = temp.next;
            }else{
                temp = temp.next;
                cur = cur.next;
            }
        }

        return head;
    }
}

1 声望1 粉丝

引用和评论

0 条评论