[leetcode] 83. Remove Duplicates from Sorted List

来源:互联网 发布:飞鹰直销软件 编辑:程序博客网 时间:2024/06/04 17:42

Question:

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.

Solution:

很简单的一道题,就是遍历删除相同的节点。特别注意指针的指向就好。可以用 1->1->1->2 作为例子考虑。

/** * 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) {        if (!head || !head->next) return head;        ListNode *prev = head, *tmp = head->next;        int last = head->val;        while (tmp) {            if (tmp->val == last) {                prev->next = tmp->next;                tmp = tmp->next;            } else {                prev = prev->next;                last = prev->val;                tmp = tmp->next;            }        }        return head;    }};
原创粉丝点击