C++删除单链表中指定元素

C++删除单链表中指定元素,第1张

// 删除单链表指定元素5
#include <iostream>
#include <vector>
using namespace std;

//节点定义:
struct ListNode {
	int val;
	ListNode* next;
	ListNode(int x) : val(x), next(nullptr) {}
};
class Solution {
public:
	ListNode* removeElements(ListNode* head, int val) {
		ListNode* dummyHead = new ListNode(0);//创造个虚拟头节点,便于 *** 作链表
		dummyHead->next = head;
		ListNode* cur = dummyHead;
		while (cur->next != NULL) {
			if (cur->next->val == val) {
				ListNode* tmp = cur->next;
				cur->next = cur->next->next;
				delete tmp;
			}
			else {
				cur = cur->next;
			}
		}
		head = dummyHead->next;//如果是删除头节点就需要这行
		delete dummyHead;
		return head;
	}
};
//创造节点
void CreateList(ListNode *head) {
	vector<int> nums = { 1,2,3,3,1,5,1 };
	ListNode *p = head;
	for (int i = 1; i < nums.size(); ++i)
	{
		p->next = new ListNode(nums[i]);
		p = p->next;
	}
}
//输出节点
void PrintList(ListNode *head) {
	ListNode *p = head;
	while (p != NULL)
	{
		cout << p->val << endl;
		p = p->next;
	}
}
int main() {
	ListNode* head = new ListNode(1);//创造头节点
	CreateList(head);
	Solution List;
	ListNode* ret = List.removeElements(head, 5);
	PrintList(ret);
	system("pause");
	return 0;
}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/866858.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-12
下一篇2022-05-12

发表评论

登录后才能评论

评论列表(0条)

    保存