[leetcode]83. 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.


删除重复的节点

一开始没注意到链表是有序的,想的方法比较蠢。将没有出现过的节点存在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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值