ListNode* deleteDuplicates-链接
实现的代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| /** * 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) { vector<int>a; while(head) { a.push_back(head->val); head=head->next; } vector<int>::iterator it=unique(a.begin(),a.end()); a.erase(it,a.end()); ListNode *ans=new ListNode (0); ListNode *x=ans; for(int i=0;i<a.size();i++) { ListNode *p=new ListNode (a[i]); x->next=p; x=p; } //返回的应该是ans-next节点,第一个节点存的不是答案中的数据 ListNode *q=ans->next; delete ans; return q; } };
|
这道题我用了个vector向量,然后去重后直接再把元素放入链表中,接着返回这个链表的头结点。