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

这道题还是很简单的,我竟然十分钟不到就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.

链表操作|删除一个有序列表中重复的数值_第1张图片
效率最佳!.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;
    }
};

你可能感兴趣的:(链表操作|删除一个有序列表中重复的数值)