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

链表无头结点

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode ln=new ListNode();
        if(head==null){
            return null;
        }
        if(head.next==null){
            return head;
        }
        ln=head;
        while(ln.next!=null) {
            if(ln.val==ln.next.val) {
                ln.next=ln.next.next;
            }
            else {
                ln=ln.next;
            }
        }
        ln=head;
        while(ln!=null) {
            System.out.print(ln.val+" ");
            ln=ln.next;
        }
        return head;
    }
}

链表有头结点

package leetcode;

public class demo_83 {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode ln=new ListNode();
        if(head==null) {
            return null;
        }
        ln=head.next;
        while(ln.next!=null) {
            if(ln.val==ln.next.val) {
                ln.next=ln.next.next;
            }
            else {
                ln=ln.next;
            }
        }
        head.printNode(head);
        return head;
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        ListNode head=new ListNode(1);
        int[] str= {-3,-3,-3,-1,-1,-1,0,0,0,5,5,5};
        head.creatnode(head, str);
        demo_83 d83=new demo_83();
        d83.deleteDuplicates(head);
    }

}

 

posted on 2021-05-09 21:10  一仟零一夜丶  阅读(55)  评论(0)    收藏  举报