删除链表重复节点 python_java删除链表中重复的节点(保留一个节点)
兩種方法實(shí)現(xiàn):
package cn.exercise.list;
import java.util.HashMap;
/**
* 刪除鏈表重復(fù)節(jié)點(diǎn)(重復(fù)節(jié)點(diǎn)只保留一個(gè))
*/
public class DeleteDuplecate {
/**
* HashMap,時(shí)間復(fù)雜度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);//加一個(gè)頭結(jié)點(diǎn)
p.next=head;
ListNode pre=p;//兩個(gè)一前一后臨時(shí)指針
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;
}
/**
* 雙重循環(huán)遍歷鏈表,時(shí)間復(fù)雜度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
結(jié)果:
after:1 2 4 5 3
總結(jié)
以上是生活随笔為你收集整理的删除链表重复节点 python_java删除链表中重复的节点(保留一个节点)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: android studio放置在函数上
- 下一篇: python 类组合_python类与对