LeetCode-Easy刷題(17) Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.


刪除排好序鏈表中重複的數字.返回一個數字不重複的鏈表

 //鏈表指針控制 雙指針
    public ListNode deleteDuplicates(ListNode head) {
        if(head ==null){
            return head;
        }
        ListNode helper = new ListNode(0);
        ListNode pre = helper;
        pre.next = head;

        while(head.next!=null){

            ListNode next = head.next;
            if(head.val != next.val){
                pre.next.next = next;
                pre = pre.next;
            }
            head = next;
        }

        if(pre.next.next!=null){
            pre.next.next=null;;
        }

        return helper.next;
    }


發佈了213 篇原創文章 · 獲贊 54 · 訪問量 43萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章