解题思路:
设置三个指针,分别是pre,current,later,pre初始值设为null,current指向头结点,later始终指向current的下一个结点。当current指向结点元素与later指向元素不等时,current后移;当current指向结点元素与later指向元素相等时,则一直后移current与later,直到current与later指向元素不等为止。此时更新指针指向,即删除链表中重复节点。
public class Solution {
public ListNode deleteDuplication(ListNode pHead) {
if (pHead == null) {
System.out.println("链表不存在");
return null;
}
//
ListNode pre = null;
ListNode current = pHead;
while (current != null) {
ListNode later = current.next;
if (later != null) {
if (current .val != later.val) {
pre = current;
current = current.next;
} else {
while (current != null && later != null && current.val == later.val ) {
current = current.next;
later = later.next;
}
//此时循环结束时,current指向重复数字的最后一个,later指向第一个数字
//断开指针的连接
if (pre != null) {
pre.next = later;
current = later;
} else {
pHead = later;
current = later;
}
}
} else {
//later == null时,
current = current.next;
}
}
return pHead;
}
}