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

  • Post author:
  • Post category:其他


// 删除单链表指定元素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;
}




版权声明:本文为weixin_49805250原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。