题目:给定排序的链表,删除重复元素,只保留重复元素第一次出现的结点;
如:给定:2–>3–>3–>5–>7–>8–>8–>8–>9–>9–>10
返回:2–>3–>5–>7–>8–>9–>10
算法思路:两个指针分别指向链表的第一个结点及第二个结点,即 pre 指向第一个结点、cur 指向第二个结点;若 pre.value == cur.value,则 pre 的 next 指向 cur 的 next ,cur 指向 cur 的 next ;若不等,则 pre 指向 cur,cur 指向 cur 的 next;直到循环结束;
若是未排序的链表,则先排序再进行重复结点的删除;
代码如下:
package neu.yimi.cn;
public class Node {
public int value;
public Node next;
public Node() {}
public Node(int value) {
this.value = value;
}
}
package neu.yimi.cn;
public class DeleteRepete {
public static void main(String[] args) {
int[] num = { 2, 3, 3, 5, 7, 8, 8, 8, 9, 9, 10 };
Node head = new Node();
Node pre = head;
for (int i = 0; i < num.length; i++) {
Node node = new Node(num[i]);
pre.next = node;
pre = node;
}
System.out.print("删除重复结点前的链表:");
print(head.next);
deleteRepeteNode(head);
System.out.print("删除重复结点后的链表:");
print(head.next);
}
/**
* 删除链表中重复的结点值,只保留第一个重复结点的值
* @param head 链表的头结点
*/
public static void deleteRepeteNode(Node head) {
Node pre = head.next;
Node cur;
while (pre != null) {
cur = pre.next;
if (cur != null && (pre.value == cur.value)) {
pre.next = cur.next;
} else {
pre = cur;
}
}
}
/**
* 打印输出链表的结点值
* @param head 链表头结点的下一个结点
*/
public static void print(Node head) {
while (head != null) {
System.out.print(head.value + " ");
head = head.next;
}
System.out.println();
}
}
结果如下: