203. 移除链表元素
#include <iostream>
#include <vector>
using namespace std;
struct ListNode {
int val;//结点值
ListNode *Next;//指向后继结点
ListNode(int x) :val(x), Next(nullptr) {}//有参构造函数
};
class Solution {
public:
ListNode* creatList(){
vector<int> nums = {1, 2, 3, 3, 1, 5, 1};
//头结点指向容器第一个值
ListNode* head =new ListNode(nums[0]);
ListNode* p =head;
for (int i = 1; i < nums.size(); ++i) {
p->Next = new ListNode(nums[i]);
p = p->Next;
}
return head;
}
void printList(ListNode* head){
ListNode* p =head;
while(p != NULL){
cout<<p->val<<endl;
p = p->Next;
}
}
ListNode* removeElements(ListNode* head, int val) {
//删除头节点
while(head != NULL && head->val == val){
ListNode* tmp = head;
head = head->Next;
delete tmp;
}
//删除非头结点
ListNode* cur = head;
while (cur != NULL && cur->Next != NULL){
if(cur->Next->val == val){
ListNode* tmp = cur->Next;
cur->Next = cur->Next->Next;
delete tmp;
} else{
cur = cur->Next;
}
}
return head;
}
};
int main(){
ListNode* Head = Solution().creatList();
ListNode* p = Solution().removeElements(Head,1);
Solution().printList(p);
system("pause");
return 0;
}