美文网首页互联网科技
链表操作|删除一个有序列表中重复的数值

链表操作|删除一个有序列表中重复的数值

作者: SweetBecca | 来源:发表于2016-09-07 13:25 被阅读58次

    这道题还是很简单的,我竟然十分钟不到就AC了,而且效率最佳12ms,有点不敢相信。

    83. Remove Duplicates from Sorted List

    Given a sorted linked list, delete all duplicates such that each element appear only once.
    For example,
    Given1->1->2,
    return1->2.
    Given1->1->2->3->3,
    return1->2->3.

    效率最佳!.png

    我自己的代码:

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* deleteDuplicates(ListNode* head) {
            ListNode* now = head;
            if(head == NULL)  return head;
            while(now -> next != NULL)
                if(now -> next -> val == now -> val) 
                    now -> next = now -> next -> next;
                else
                    now = now -> next;
            return head;
        }
    };
    

    相关文章

      网友评论

        本文标题:链表操作|删除一个有序列表中重复的数值

        本文链接:https://www.haomeiwen.com/subject/gdujettx.html