1.遍历链表
2.双重循环遍历,外循环遍历链表,假设外循环当前结点为cur,内循环从cur开始遍历,若碰到与cur所指结点相同,则删除这个重复结点。
import java.util.Hashtable;
public class DelDup {
public static void main(String[] args){
Node n1=new Node(2);
Node n2=new Node(3);
Node n3=new Node(5);
Node n4=new Node(9);
Node n5=new Node(9);
n1.next=n2;
n2.next=n3;
n3.next=n4;
n4.next=n5;
//Node n=new DelDup().delDup(n1);
Node n=new DelDup().delDup2(n1);
while (n!=null){
System.out.print(n.data+" ");
n=n.next;
}
}
//方法1.遍历链表
public Node delDup(Node head){
//保存前一结点的指针
Hashtable<Integer,Integer> table = new Hashtable<Integer, Integer>();
Node tmp=head;
Node pre=null;
while(tmp!=null) {
if (table.containsKey(tmp.data)){
pre.next=tmp.next;
}else{
table.put(tmp.data,1);
pre=tmp;
}
tmp=tmp.next;
}
return head;
}
//方法2:双重循环遍历
public Node delDup2(Node head){
Node p=head;
while(p!=null){
Node q=p;
while(q.next!=null){
if(p.data==q.next.data){
q.next=q.next.next;
}else{
q=q.next;
}
}
p=p.next;
}
return head;
}
}