码迷,mamicode.com
首页 > 其他好文 > 详细

链表去重

时间:2019-10-22 18:33:50      阅读:53      评论:0      收藏:0      [点我收藏+]

标签:cat   node   out   print   rate   问题:   void   去掉   xcopy   

问题:去掉链表中的重复结点?
适用:链表有序,可以有多重
这里定义三个指针,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);
    }

        }

链表去重

标签:cat   node   out   print   rate   问题:   void   去掉   xcopy   

原文地址:https://blog.51cto.com/14232658/2444524

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!