删除链表重复元素,只保留一个

/**
 * @author yuchen
 * @version 1.0
 * @date 2020-05-26 16:21
 *
 * 删除链表重复元素,只保留一个
 * 比如
 * 1, 2, 2, 2, 2, 4, 4, 5, 6, 6, 9, 8, 8
 *
 * 我们的方法处理以后的结果是
 *
 * 1 -> 2 -> 4 -> 5 -> 6 -> 9 -> 8 ->
 */
public class DeleteNodeSame {

    public static void main(String[] args) {
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(2);
        Node node4 = new Node(2);
        Node node5 = new Node(4);
        Node node6 = new Node(4);
        Node node7 = new Node(5);
        Node node8 = new Node(6);
        Node node9 = new Node(7);

        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node6;
        node6.next = node7;
        node7.next = node8;
        node8.next = node9;

        Node node = del2(node1);
        while (node!=null){
            System.out.println(node.data);
            node = node.next;
        }
    }

    static class Node{
        int data;
        Node next;
        public Node(int data){
            this.data = data;
        }
    }

    public static Node del2(Node head){

        if(head == null){
            return null;
        }

        Node preNode = head;
        Node curNode = head.next;

        while (curNode!=null){
            Node temp = curNode.next;

            if(preNode.data == curNode.data){
                preNode.next = temp;
                curNode = temp;
            }else{
                preNode = curNode;
                curNode = temp;
            }
        }

        return head;
    }
}

 

你可能感兴趣的:(简单小算法)