83. 刪除排序鏈表中的重複元素

83. 刪除排序鏈表中的重複元素

一、題目介紹

給定一個排序鏈表,刪除全部重複的元素,使得每一個元素只出現一次。測試

試題連接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/code

二、java

2.一、使用額外的空間:

public static ListNode deleteDuplicates(ListNode head) {
        if(head == null) return null;

        ListNode newNode = new ListNode(-1);
        newNode.val = head.val;
        newNode.next = null;

        ListNode p = newNode;
        while(head != null) {
//            System.out.println(newNode);
            if(head.val != p.val) {
                p.next = head;
                p = p.next;
            }else {
                head = head.next;
                p.next = null;
            }
        }
        return newNode;
    }

輸出結果:blog

2.二、不使用額外的空間:

public static ListNode deleteDuplicates(ListNode head) {
        if(head == null) return null;

        ListNode p1 = head;
        ListNode p2 = head.next;

        while (p2 != null) {
            if(p2.val == p1.val) {
                p1.next = p2.next;
                p2 = p2.next;
            }else {
                p2 = p2.next;
                p1 = p1.next;
            }
        }
        return head;
    }

測試結果:排序

三、C

3.一、使用額外的空間

struct ListNode* deleteDuplicates(struct ListNode* head){
        if(head == NULL) return NULL;

        struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode));
        newNode->val = head->val;
        newNode->next = NULL;

        struct ListNode* p = newNode;
        while(head != NULL) {
            if(head->val != p->val) {
                p->next = head;
                p = p->next;
            }else {
                head = head->next;
                p->next = NULL;
            }
        }
        return newNode;
}

測試結果:leetcode

3.二、不使用額外的空間

struct ListNode* deleteDuplicates(struct ListNode* head){
    if(head == NULL) return NULL;

    struct ListNode* p1 = head;
    struct ListNode* p2 = head->next;

    while (p2 != NULL) {
        if(p2->val == p1->val) {
            p1->next = p2->next;
            p2 = p2->next;
        }else {
            p2 = p2->next;
            p1 = p1->next;
        }
    }
    return head;
}

測試結果:rem

相關文章
相關標籤/搜索