题目

存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除所有重复的元素,使每个元素 只出现一次 。

返回同样按升序排列的结果链表。

示例 1:

输入:head = [1,1,2]
输出:[1,2]
示例 2:

输入:head = [1,1,2,3,3]
输出:[1,2,3]

提示:

链表中节点数目在范围 [0, 300] 内
-100 <= Node.val <= 100
题目数据保证链表已经按升序排列

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解

1.迭代

  1. /**
  2. * Definition for singly-linked list.
  3. * function ListNode(val, next) {
  4. * this.val = (val===undefined ? 0 : val)
  5. * this.next = (next===undefined ? null : next)
  6. * }
  7. */
  8. /**
  9. * @param {ListNode} head
  10. * @return {ListNode}
  11. */
  12. var deleteDuplicates = function (head) {
  13. const dummy = head
  14. while (head && head.next) {
  15. if (head.next.val === head.val) {
  16. head.next = head.next.next
  17. } else {
  18. head = head.next
  19. }
  20. }
  21. return dummy
  22. };
  1. 递归
    /**
    * Definition for singly-linked list.
    * function ListNode(val, next) {
    *     this.val = (val===undefined ? 0 : val)
    *     this.next = (next===undefined ? null : next)
    * }
    */
    /**
    * @param {ListNode} head
    * @return {ListNode}
    */
    var deleteDuplicates = function (head) {
     //    递归
     if (!head) {
         return null
     }
     const nxt = deleteDuplicates(head.next)
     if (nxt && head.val === nxt.val) {
         head.next = nxt.next
     }
     return head
    };