链表去重Java

链表去重Java_第1张图片

去除掉链表中重复的元素,两种方法:

    static class ListNode{
        private int val;
        private ListNode next;

        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    ", next=" + next +
                    '}';
        }
    }
    public static void main(String[] args) {
        ListNode node3 = new ListNode(2, null);
        ListNode node2 = new ListNode(1, node3);
        ListNode node1 = new ListNode(1, node2);
        System.out.println("去除链表中的重复元素为:" + deleteDuplicates(node1));
        ListNode next5 = new ListNode(3, null);
        ListNode next4 = new ListNode(3, next5);
        ListNode next3 = new ListNode(2, next4);
        ListNode next2 = new ListNode(1, next3);
        ListNode next1 = new ListNode(1, next2);
        System.out.println("去除链表中的重复元素为:" + deleteDuplicates1(next1));

    }

    //删除链表中的重复的元素
    private static ListNode deleteDuplicates(ListNode head) {
        if (head == null) {
            return head;
        }
        ListNode currNode = head;
        while (currNode.next != null) {
            if (currNode.val == currNode.next.val) {
                currNode.next = currNode.next.next;
            } else {
                currNode = currNode.next;
            }
        }
        return head;
    }

    //递归去除重复元素
    private static ListNode deleteDuplicates1(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        head.next = deleteDuplicates1(head.next);
        return head.val == head.next.val? head.next:head;
    }

去除链表中的重复元素为:ListNode{val=1, next=ListNode{val=2, next=null}}
去除链表中的重复元素为:ListNode{val=1, next=ListNode{val=2, next=ListNode{val=3, next=null}}}

你可能感兴趣的:(链表,java,数据结构)