typescript实现
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
function deleteDuplicates(head: ListNode | null): ListNode | null {
let start = head
while(start) {
const next = start.next
next && start.val === next.val && (start.next = next.next)
start = start.next && start.val === start.next.val ? start : start.next
}
return head
};
java实现
/**
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
// TODO: 快慢指针
if (head == null) return head;
ListNode slow = head;
ListNode fast = head.next;
while (fast != null){
if (slow.val != fast.val) {
slow.next = fast;
slow = fast;
}
fast = fast.next;
}
slow.next = null;
return head;
}
}
// TODO: 单指针下一步
//class Solution {
// public 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;
// }
//}
评论区