定义main函数,调用给出的建立、输出、插入、删除等函数,验证单链表
时间: 2024-01-31 15:02:32 浏览: 23
好的,以下是一个简单的实现:
```C++
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
void printList(ListNode* head) {
ListNode* curr = head;
while (curr != NULL) {
cout << curr->val << "->";
curr = curr->next;
}
cout << "NULL" << endl;
}
void insertNode(ListNode*& head, int val) {
ListNode* newNode = new ListNode(val);
if (head == NULL) {
head = newNode;
}
else {
ListNode* curr = head;
while (curr->next != NULL) {
curr = curr->next;
}
curr->next = newNode;
}
}
void deleteNode(ListNode*& head, int val) {
if (head == NULL) {
return;
}
if (head->val == val) {
ListNode* temp = head;
head = head->next;
delete temp;
}
else {
ListNode* curr = head;
while (curr->next != NULL && curr->next->val != val) {
curr = curr->next;
}
if (curr->next != NULL) {
ListNode* temp = curr->next;
curr->next = temp->next;
delete temp;
}
}
}
int main() {
ListNode* head = NULL;
insertNode(head, 1);
insertNode(head, 2);
insertNode(head, 3);
printList(head);
deleteNode(head, 2);
printList(head);
return 0;
}
```
在这个示例中,我们定义了一个 `ListNode` 结构体,其中包含一个 `int` 类型的值和一个指向下一个节点的指针。然后我们实现了 `printList`、`insertNode` 和 `deleteNode` 函数,分别用于输出链表、插入节点和删除节点。最后在 `main` 函数中调用这些函数,以验证单链表的正确性。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)