[leetcode]83. Remove Duplicates from Sorted List

来源:互联网 发布:淘宝代充平台 编辑:程序博客网 时间:2024/06/06 03:27

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.


删除重复的节点

一开始没注意到链表是有序的,想的方法比较蠢。将没有出现过的节点存在hashmap,存在的则放在stack中,再去删除stack中的节点。

deleteNode()删除节点的原理是:如要删除i节点,先把i的下一个节点j的数据复制到i,然后把i指向j的下一个节点。这样就省去了从头节点开始查找。如果

要删除的节点为最后一个节点,仍然从头节点遍历。平均时间复杂度仍为O(1)

代码如下:

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution { public ListNode deleteDuplicates(ListNode head) {        HashMap<ListNode,Integer> map=new HashMap<>();        Stack<ListNode> stack=new Stack<>();        ListNode p=head;        while(p!=null){            if(map.containsValue(p.val)){            stack.push(p);            }else{            map.put(p, p.val);            }            p=p.next;        }        while(!stack.empty()){        deleteNode(head, stack.pop());        }        return head;    }        public void deleteNode(ListNode head,ListNode node){        if(head==null||node==null){            return;        }        else if(head==node){            head=null;        }        else{            if(node.next==null){                ListNode p=head;                while(p.next.next!=null){                    p=p.next;                }                p.next=null;            }            else{                node.val=node.next.val;                node.next=node.next.next;            }        }    }}


由于链表是有序的,所以节点是否重复,只需要与它的下一个比较就可以了

代码如下:

public class Solution {    public ListNode deleteDuplicates(ListNode head) {        if (head == null) {            return null;        }        ListNode node = head;        while (node.next != null) {            if (node.val == node.next.val) {                node.next = node.next.next;            } else {                node = node.next;            }        }        return head;    }}



1 0
原创粉丝点击