链表去重

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了链表去重相关的知识,希望对你有一定的参考价值。

问题:去掉链表中的重复结点?
适用:链表有序,可以有多重
这里定义三个指针,prev,p1,p2
prev.next=p1;
p1=head;
p2=head.next;
如果p1.val=p2.val,三个指针分别向后移一位。
如果p1.val!=p2.val,p2后移,
直到两者不相等为止。
然后prev.next=p2;(判断prev是否为null)
p1=p2;
p2=p2.next;(判断p2是否为null)

public class Solution{
 public Node deleteDuplicated(Node head) {//链表去重,留下一个
        if (head == null) {
            return head;
        }

        Node prev = null;
        Node p1 = head;
        Node p2 = head.next;

        while (p2 != null) {
            if (p1.val != p2.val) {
                prev = p1; p1 = p2; p2 = p2.next;
            } else {
                while (p2 != null && p2.val == p1.val) {//刚进来p21=null。执行一次后可能为null,所以在这里要保证
                    p2 = p2.next;
                }

                if (prev == null) {
                    head = p2;
                } else {
                    prev.next = p2;
                }

                p1 = p2;
                if (p2 != null) {
                    p2 = p2.next;
                }
            }
        }

        return head;
    }
        private static Node prepareListForSeparateX3() {
        Node n1 = new Node(9);
        Node n2 = new Node(1);
        Node n3 = new Node(8);
        Node n4 = new Node(2);
        Node n5 = new Node(7);

        n1.next = n2; n2.next = n3; n3.next = n4;
        n4.next = n5;

        return n1;
    }
public class Node {
    int val;
    Node next = null;

    Node(int val) {
        this.val = val;
    }

    public String toString() {
        return String.format("Node(%d)", val);
    }
}

    private static void print(Node head) {
        for (Node cur = head; cur != null; cur = cur.next) {
            System.out.print(cur + " ");
        }
        System.out.println();
    }
 public static void main(String[] args) {
        Solution solution = new Solution();
        testSeparateX(solution);
        testDeleteDuplicated(solution);
        testComplexCopy(solution);
    }

        }

以上是关于链表去重的主要内容,如果未能解决你的问题,请参考以下文章

pat L2-002 链表去重

L2-002 链表去重 (25 分)

链表去重

链表去重

链表去重

L2-002 链表去重(链表+模拟)