标签:cat node out print rate 问题: void 去掉 xcopy
问题:去掉链表中的重复结点?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