83. 删除排序链表中的重复元素🔖链表

83. 删除排序链表中的重复元素🔖链表

83. 删除排序链表中的重复元素typescript实现/** * Definition for singly-linked list. * class ListNode { * val: number * next: ListNode | null * co...

2020年11月30日
245字
7 阅读

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;
//    }
//}

文章评论区

欢迎留言交流

未登录,请先注册或登录后发表评论。

Leave comment