删除无序链表中值重复出现的节点
2017-11-06 11:26
393 查看
import java.util.HashSet;
//删除无序链表中值重复出现的节点
public class DelSameList{
//节点的定义
public static class Node{
int value;
Node next;
public Node(int data)
{
this.value=data;
}
}
//(一、哈希表法 时间复杂度O(n),空间复杂度O(n))删除无序链表中值重复出现的节点
public static void delSameList(Node head)
{
if(head==null)
{
return ;
}
HashSet<Integer> set=new HashSet<Integer>(); //存储不相同节点的值
Node p=head;
Node cur=head.next;
set.add(head.value); //首先加入头节点
while(cur!=null)
{
if(set.contains(cur.value))
{
p.next=cur.next; //删除cur这个节点
}else{
set.add(cur.value);
p=cur;
}
cur=cur.next;
}
}
//(一、选择排序法 时间复杂度O(n*n),空间复杂度O(1))删除无序链表中值重复出现的节点
public static void delSameList2(Node head)
{
if(head==null)
{
return;
}
Node cur=head;
Node pre=null;
Node next=null;
while(cur!=null)
{
pre=cur;
next=cur.next;
while(next!=null)
{
if(cur.value==next.value)
{
pre.next=next.next; //删除next节点
}
else
{
pre=next; //pre向下移动一个节点
}
next=next.next;
}
cur=cur.next;
}
}
//打印链表
public static void PrintList(Node head)
{
while(head!=null)
{
System.out.print(head.value+" ");
head=head.next;
}
System.out.println();
}
public static void main(String[]args)
{
Node node=new Node(1);
node.next=new Node(2);
node.next.next=new Node(3);
node.next.next.next=new Node(3);
node.next.next.next.next=new Node(4);
node.next.next.next.next.next=new Node(4);
node.next.next.next.next.next.next=new Node(2);
node.next.next.next.next.next.next.next=new Node(1);
node.next.next.next.next.next.next.next.next=new Node(1);
PrintList(node);
delSameList2(node); //删除重复的节点
PrintList(node);
}
}
相关文章推荐
- 链表问题---删除无序单链表中值重复出现的节点
- [算法]删除无序单链表中值重复出现的节点
- 算法优解(8)-删除无序单链表中重复出现的节点
- 【IT笔试面试题整理】删除无序链表中重复的节点
- 删除有序链表中的重复节点
- 从链表中删除重复节点
- 剑指offer 57 - 删除链表中重复的节点
- 删除链表中重复的节点
- 删除排序链表的重复节点
- 《剑指offer》删除链表中重复的节点
- 删除链表中重复的节点
- 剑指offer系列之五十八:删除链表中重复的节点
- 删除链表中重复的节点
- 删除链表重复节点
- 删除链表中重复的节点
- 56、删除链表中的重复节点
- 【链表】删除链表中连续重复的节点
- 剑指Offer—56—删除链表中重复的节点
- 剑指offer-删除链表重复节点
- 算法系列之-删除重复出现的节点