Leetcode: Remove Duplicates from Sorted List

来源:互联网 发布:当尼采哭泣知乎 编辑:程序博客网 时间:2024/06/07 02:32

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.

做个简单的,找些信心。13个小时的地方,给我唯一的动力。

/** * 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 == NULL || head->next == NULL) {            return head;        }                ListNode *prev = head;        ListNode *cur = head->next;        while (cur != NULL) {            if (cur->val != prev->val) {                prev->next = cur;                prev = cur;            }            cur = cur->next;        }        prev->next = cur;                return head;    }};

===================第二次========================

/** * 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 == NULL || head->next == NULL) {            return head;        }                ListNode *cur = head->next;        ListNode *prev = head;        while (cur != NULL) {            if (cur->val != prev->val) {                prev->next = cur;                prev = cur;            }            cur = cur->next;        }        prev->next = NULL;                return head;    }};


0 0
原创粉丝点击