题目
题解
代码
/** * Definition for singly-linked list. public class ListNode { int val; ListNode * next; ListNode(int x) { val = x; } } */
public class code83 {
// public static ListNode deleteDuplicates(ListNode head) {
// if (head == null) {
// return head;
// }
// ListNode dummy = new ListNode(-100);
// dummy.next = head;
// ListNode slow = dummy;
// ListNode fast = dummy.next;
// while (fast != null) {
// if (slow.val == fast.val) { // 如果存在重复元素的话
// fast = fast.next;
// slow.next = fast;
// } else { // 如果不存在重复元素的话
// slow = slow.next;
// fast = fast.next;
// }
// }
// return dummy.next;
// }
public static ListNode deleteDuplicates(ListNode head) {
ListNode cur = head;
while (cur != null && cur.next != null) {
if (cur.val == cur.next.val) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return head;
}
public static void print(ListNode node) {
if (node == null) {
return;
}
ListNode current = node;
while (current != null) {
System.out.print(current.val + " -> ");
current = current.next;
}
System.out.println("NULL");
}
public static void main(String[] args) {
ListNode listNode1 = new ListNode(1);
ListNode listNode2 = new ListNode(1);
ListNode listNode3 = new ListNode(2);
ListNode listNode4 = new ListNode(3);
ListNode listNode5 = new ListNode(3);
listNode1.next = listNode2;
listNode2.next = listNode3;
listNode3.next = listNode4;
listNode4.next = listNode5;
ListNode head = deleteDuplicates(listNode1);
print(head);
}
}