删除链表重复节点 python_java删除链表中重复的节点(保留一个节点)

两种方法实现:

package cn.exercise.list;

import java.util.HashMap;

/**

* 删除链表重复节点(重复节点只保留一个)

*/

public class DeleteDuplecate {

/**

* HashMap,时间复杂度o(n)

* @param head

* @return

*/

public static ListNode deleteDulp(ListNode head){

if(head==null || head.next==null)

return head;

HashMap map=new HashMap();

ListNode p=new ListNode(-1);//加一个头结点

p.next=head;

ListNode pre=p;//两个一前一后临时指针

ListNode cur=p.next;

while(pre!=null && pre.next!=null){

if(map.containsKey(cur.val)){

pre.next=cur.next;

cur=cur.next;

}else{

map.put(cur.val,1);

pre=cur;

cur=cur.next;

}

}

return p.next;

}

/**

* 双重循环遍历链表,时间复杂度o(n^2)

* @param head

* @return

*/

public static ListNode deleteDulp2(ListNode head){

if(head==null || head.next==null)

return head;

ListNode p=head;

ListNode root=p;

while(p!=null){

ListNode q=p;

while(q.next!=null){

if(p.val==q.next.val){

q.next=q.next.next;

}else{

q=q.next;

}

}

p=p.next;

}

return root;

}

public static void main(String[] args){

ListNode root=new ListNode(1);

ListNode b=new ListNode(2);

ListNode c=new ListNode(4);

ListNode d=new ListNode(2);

ListNode e=new ListNode(5);

ListNode f=new ListNode(4);

ListNode g=new ListNode(3);

ListNode h=new ListNode(5);

root.next=b;

b.next=c;

c.next=d;

d.next=e;

e.next=f;

f.next=g;

g.next=h;

while(root!=null){

System.out.print(root.val+" ");

root=root.next;

}

System.out.print("after:");

ListNode pre=deleteDulp2(root);

while(pre!=null){

System.out.print(pre.val+" ");

pre=pre.next;

}

}

}

before:1 2 4 2 5 4 3 5

结果:

after:1 2 4 5 3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值