[leetcode]Remove Duplicates from Sorted List

来源:互联网 发布:软件质量品质管理 编辑:程序博客网 时间:2024/04/30 00:06

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.

链表的简单应用,一开始没有加if(head==NULL) return head;错了一次,以后要注意=.=

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    map<int,bool> ans;    ListNode *deleteDuplicates(ListNode *head) {        ListNode * i,*j,*res,*ans;        if(head==NULL) return head;        res->val = head->val;        res->next= NULL;        ans = res;        bool flag;        for(i=head->next;i!=NULL;i=i->next){            flag = false;            for(j=head;j!=NULL && j!=i;j=j->next){                if(j->val==i->val) {                    flag = true;                    break;                }            }            if(flag==false){                res->next = i;                res=res->next;            }        }        res->next = NULL;        return ans;    }};
0 0
原创粉丝点击