关于leetcode个人解题总结:刷题11删除排序链表中的重复元素

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;
    }
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理