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

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

1、题目介绍

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

试题链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/

2、java

2.1、使用额外的空间:

    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;
    }

输出结果:

2.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;
    }

测试结果:

3、C

3.1、使用额外的空间

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;
}

测试结果:

3.2、不使用额外的空间

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;
}

测试结果:

posted @ 2020-03-02 20:17  孤傲的咸鱼  阅读(768)  评论(0编辑  收藏  举报