#include <stdio.h>
#include <stdlib.h>
//#include <cstdio>
//#include <vector>
#include<iostream>
#include<cstdlib>
using namespace std;
//定义一个结构体 ListNode的结构
struct ListNode
{
int val; //当前结点的值用val表示
struct ListNode *next; //指向下一个结点的指针用next表示
ListNode(int x) : val(x), next(NULL) { } //初始化当前结点值为x,指针为空
};
void print(ListNode *head) //打印输出链表
{
ListNode *p = head;
while (p != NULL)
{
cout << p->val;
p = p->next;
}
}
ListNode* CreateListNode(ListNode* pHead) // 创建链表
{
ListNode* p = pHead; // 声明移动指针,最开始指向头结点
for (int i = 1; i < 10; ++i)
{
ListNode* pNewNode; // 声明链表 pNewNode 来保存数据,pNewNode 就是一个链表的节点
pNewNode = new ListNode(0); // 初始化变量 pNewNode
pNewNode->val = i; // 将新节点的值赋值为 i
pNewNode->next = NULL;
p->next = pNewNode; // p的下一节点指向这个新的节点,将此节点与头节点连接
p = pNewNode; // p节点指向这个新的节点,向后移动指针,以便下一次链接;p一直指向链表最后的一个节点
}
return pHead;
}
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;
}
};
int main()
{
/*
ListNode* head; // 声明头节点
head = new ListNode(0); // 头节点需要赋值才能调用
ListNode* p = CreateListNode(head); // 引用头结点创建链表
print(p); //引用打印
system("pause");
*/
ListNode* head;
head = new ListNode(0);
ListNode* p = CreateListNode(head);
printListNode(p);
Solution solution1;
ListNode* p1 = solution1.removeElements(p, 3);
printListNode(p1);
return 0;
}
2_2 c++ 链表节点的定义,创建, 以及删除;
于 2022-02-17 11:57:46 首次发布