[LeetCode]83. Remove Duplicates from Sorted List

来源:互联网 发布:坏坏的女人有魅力知乎 编辑:程序博客网 时间:2024/06/06 00:27

[LeetCode]83. Remove Duplicates from Sorted List

题目描述

这里写图片描述

思路

遍历比较,删除值相同的节点即可

代码

#include <iostream>#include <vector>using namespace std;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;        while (cur) {            if (cur->next && cur->val == cur->next->val) {                cur->next = cur->next->next;            }            else {                cur = cur->next;            }        }        return head;    }    void printList(ListNode* head) {        while (head) {            cout << head->val << " ";            head = head->next;        }        cout << endl;    }    ListNode* vector2list(vector<int> nums) {        if (nums.size() == 0)            return NULL;        ListNode* head = new ListNode(nums[0]), *iter = head;        for (int i = 1; i < nums.size(); ++i) {            ListNode* temp = new ListNode(nums[i]);            iter->next = temp;            iter = iter->next;        }        return head;    }};int main() {    vector<int> nums = { 1,1,1,1,1 };    Solution s;    ListNode* head = s.vector2list(nums);    s.printList(head);    s.printList(s.deleteDuplicates(head));    system("pause");    return 0;}
0 0