给定一个排序链表,删除所有重复的元素使得每个元素只留下一个。
案例:
给定 1->1->2,返回 1->2
给定 1->1->2->3->3,返回 1->2->3
详见:https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/

Java实现:

递归实现:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        if(head==null||head!=null&&head.next==null){
            return head;
        }
        ListNode tmp=head;
        ListNode next=deleteDuplicates(head.next);
        if(next!=null){
            if(tmp.val==next.val){
                tmp.next=next.next;
            }
        }
        return head;
    }
}

 非递归实现:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode cur=head;
        while(cur!=null){
            while(cur.next!=null&&cur.val==cur.next.val){
                cur.next=cur.next.next;
            }
            cur=cur.next;
        }
        return head;
    }
}

 

相关文章:

  • 2021-08-11
  • 2021-08-17
  • 2022-12-23
  • 2021-10-22
  • 2022-12-23
  • 2021-11-22
  • 2021-06-16
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-05-30
  • 2022-03-09
  • 2021-06-08
  • 2021-11-15
  • 2022-02-23
  • 2021-09-11
相关资源
相似解决方案