Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

83 删除排序链表中的重复元素 #18

Closed
sailei1 opened this issue May 16, 2019 · 0 comments
Closed

83 删除排序链表中的重复元素 #18

sailei1 opened this issue May 16, 2019 · 0 comments

Comments

@sailei1
Copy link
Owner

sailei1 commented May 16, 2019

给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。

示例 1:

输入: 1->1->2
输出: 1->2
示例 2:

输入: 1->1->2->3->3
输出: 1->2->3

解法:
1 当前节点的值跟 下一个节点的值相同
2 当前节点的下一个节点 指向下一个下一个的节点 (注意是循环)
3 递归查找 重复 1 2 步
4 找到最后一个节点 跳出

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var deleteDuplicates = function(head) {
      if(!head){return head;}  //尾部返回
      while(head.next&&head.val === head.next.val){
            head.next=head.next.next;    //   当前值跟下一个值 一样时, 跳过当前值
      }
     // console.log(head.val);
    deleteDuplicates(head.next); //依次递归
    return head
    
};

@sailei1 sailei1 closed this as completed May 17, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant