没有回收,可能会造成内存泄露
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
#include<fstream> #include <vector> #include<string> #include<iostream> #include <sstream> #include <stdexcept> using namespace std; struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } }; class Solution { public: //没有回收节点,会造成内存泄露 ListNode* deleteDuplication(ListNode* pHead) { if (pHead == NULL||pHead->next==NULL){ return pHead; } ListNode *newHead = pHead; while (pHead->next) { if (pHead->val == pHead->next->val){ while (pHead->val == pHead->next->val) { pHead->next = pHead->next->next; } } pHead = pHead->next; } pHead = newHead; return pHead; } }; int main() { Solution s; ListNode l1(1), l2(2), l3(3), l4(3), l5(4), l6(4), l7(5); (&l1)->next = &l2; (&l2)->next = &l3; (&l3)->next = &l4; (&l4)->next = &l5; (&l5)->next = &l6; (&l6)->next = &l7; ListNode *l= s.deleteDuplication(&l1); while (l){ cout << l->val; l = l->next; } system("pause"); return 0; }