一、题目描述
二、示例
三、难度
简单
四、代码
Java版
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public class Solution {
public ListNode deleteDuplicates(ListNode head) {
if (head == null) return null;
ListNode slow = head, fast = head.next;
while (fast != null) {
if (slow.val != fast.val) {
slow.next = fast;
slow = slow.next;
}
fast = fast.next;
}
slow.next = null;
return head;
}
public static void main(String[] args) {
ListNode node4 = new ListNode(3);
ListNode node3 = new ListNode(3,node4);
ListNode node2 = new ListNode(2,node3);
ListNode node1 = new ListNode(1,node2);
ListNode head = new ListNode(1,node1);
ListNode list = new Solution().deleteDuplicates(head);
while (list != null) {
System.out.print(list.val+" ");
list = list.next;
}
}
}
|