問題:去掉鏈表中的重複結點?
適用:鏈表有序,能夠有多重
這裏定義三個指針,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)ide
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); } }