分析: 整个过程分三个阶段
1、首先创建链表(单向)
2、对链表进行去重
去重的逻辑,需要两个引用,一个指向当前节点,一个指向前节点,
若当前节点的数据重复,前置节点的下一跳为当前节点的下一跳节点,前置节点不移动,只移动当前节点向前。
若当前节点的数据不重复,前置节点指向当前节点,当前节点指向下一跳。
3、打印去重后的数据
pojo:
package com.bobo.pojo;
public class LinkedNode
{
private LinkedNode next;
private Object data;
public LinkedNode getNext() {
return next;
}
public void setNext(LinkedNode next) {
this.next = next;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
@Override
public String toString() {
return "LinkedNode [next=" + next + ", data=" + data + "]";
}
}
service:
package com.bobo.service;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import com.bobo.pojo.LinkedNode;
/**
* java 链表中去除重复的节点
* @author harrybobo
*
*/
public class LinkedNodeService
{
public static void main(String[] args)
{
//1.首先生成链表
LinkedNode startNode = createLinkedNodes(10);
//2.进行去重复
checkRepeat(startNode);
//3.打印
sysoData(startNode);
}
private static void sysoData(LinkedNode startNode)
{
System.out.println();
while (startNode != null)
{
System.out.println(startNode.getData());
startNode = startNode.getNext();
}
}
private static void checkRepeat(LinkedNode startNode)
{
List<Object> tmpList = new ArrayList<Object>();
tmpList.add(startNode.getData());
//创建两个引用
LinkedNode current = startNode.getNext();
while (current != null)
{
if (tmpList.contains(current.getData()))
{
//若set中已存在,需要删除
startNode.setNext(current.getNext());
}
else
{
tmpList.add(current.getData());
startNode = current;
}
current = current.getNext();
}
}
private static LinkedNode createLinkedNodes(int aSize)
{
LinkedNode startNode = new LinkedNode();
Random random = new Random();
LinkedNode returnNode = startNode;
int i = 0;
while (i < aSize)
{
if (returnNode.getData() == null)
{
returnNode.setData(random.nextInt(10));
LinkedNode next = new LinkedNode();
returnNode.setNext(i == aSize-1 ? null : next);
System.out.println(returnNode.getData());
returnNode = next;
i++;
}
}
return startNode;
}
}