#include
using namespace std;
//Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode *dummy = new ListNode(0);
dummy->next = head;
ListNode *pre = dummy;
//方案一
while (pre->next != NULL){
if (pre->next->val == val) {
pre->next = pre->next->next;
}
else{
pre = pre->next;
}
}
return dummy->next;
//方案二(此方案存在bug,若最后一个值为val,无法删除)
//while (head->next != NULL) {
// if (head->val == val) {
// pre->next = head->next;
// head = head->next;
// }
// else {
// pre = head;
// head = head->next;
// }
//}
}
};
ListNode* NUM(char num[], int size) {
ListNode *L1 = new ListNode(NULL);
ListNode *pre = L1;
for (int i = 0; i < size; i++)
{
ListNode *p = new ListNode(NULL);
p->val = num[i];
pre->next = p;
pre = p;
p->next = NULL;
}
return L1->next;
}
void print(ListNode *L) {
for (int i = 0; i < 5; i++)
{
cout << L->val << endl;
L = L->next;
}
}
void test01() {
char num[] = { 1,2,6,3,4,5,6 };
int m_size = sizeof(num);
ListNode *L1 = NUM(num, m_size);
Solution S;
ListNode *L2 = S.removeElements(L1, 6);
print(L2);
}
int main()
{
test01();
system("pause");
return 0;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)