题意:只要链表中元素x重复出现了,删除所有元素x(刚开始还读错题了……)
题解:
- 在表头前添加链表的虚拟节点dummy
- 遍历链表
(1)如果当前节点cur的下一个节点cur.next和cur.next.next相等,则意味着出现了重复元素,记录元素值,从cur.next开始挨个删除重复元素
(2)如果不等,则后移cur - 终止条件:cur.next == null || cur.next.next = null;
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head == null) return null;
ListNode dummy = new ListNode(0, head);
ListNode cur = dummy;
while(cur.next != null && cur.next.next != null) {
if(cur.next.val == cur.next.next.val) {
int x = cur.next.val;
while(cur.next != null && cur.next.val == x) {
cur.next = cur.next.next;
}
} else {
cur = cur.next;
}
}
return dummy.next;
}
}