单链表删除所有重复元素
直接上代码:
节点类:
package arraystolist; /** * 节点类 * @author hanxiaofan * */ public class Node { private final int value; //数据一旦放入就不可更改 private Node next; public Node(int value) { this.value = value; this.next = null; } public Node getNext() { return next; } public void setNext(Node next) { this.next = next; } public int getValue() { return value; } public static void printLiskedList(Node node) { while(node != null) { System.out.print(node.getValue()); System.out.print(" "); node = node.getNext(); } System.out.println(""); } }
操作类:
package arraystolist; import java.util.Arrays; import java.util.List; /** * 删除链表中所有指定的元素 * 如: 1->2->3->2->5->null 删除2 * 删除后 1->3->5->null * * @author hanxiaofan * */ public class LinkedListDeletor { /** * 使用递归创建单向链表。最后一个元素指向null * @param data * @return */ public Node createLinkedList(List<Integer> data) { if(data.isEmpty()) { //如果为空返回null return null; } Node firstNode = new Node(data.get(0)); //每次取第一个元素 Node secondNode = createLinkedList(data.subList(1, data.size()));//第二个元素从下标为1开始取余下list firstNode.setNext(secondNode); return firstNode; } /** * 删除操作 * * @param head * 链表头节点 * @param value * 指定的值 * @return */ public Node deleteIfEquals(Node head, int value) { while (head != null && head.getValue() == value) { // 头节点等于指定值 head = head.getNext(); // 指向下一个 } if (head == null) { // 如果当前节点的头节点是null,则退出 return null; } Node pre = head; while (pre.getNext() != null) { // 不为空则是进入循环不变式 if (pre.getNext().getValue() == value) { // 如果下一个节点的值相等,则删除 pre.setNext(pre.getNext().getNext()); // 将当前节点的值指向后一个的后一个 } else { pre = pre.getNext(); // 不等于则不改变 } } return head; } public static void main(String[] args) { LinkedListCreator creator = new LinkedListCreator(); LinkedListDeletor deletor = new LinkedListDeletor(); Node.printLiskedList(deletor.deleteIfEquals(creator.createLinkedList(Arrays.asList(2, 2, 2, 3, 2, 2)), 2)); } }