问题 A: 实验11_4_初识链表
时间: 2023-08-16 15:07:01 浏览: 84
这道题目是要求我们实现链表的基本操作,包括创建链表、插入节点、删除节点、遍历链表等。以下是一个简单的链表实现代码示例:
```c++
#include <iostream>
using namespace std;
// 定义链表节点结构体
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
// 创建链表
ListNode* createList(int nums[], int n) {
if (n == 0) return NULL;
ListNode *head = new ListNode(nums[0]);
ListNode *cur = head;
for (int i = 1; i < n; i++) {
cur->next = new ListNode(nums[i]);
cur = cur->next;
}
return head;
}
// 插入节点
void insertNode(ListNode *&head, int pos, int val) {
if (pos < 0) return;
if (pos == 0) {
ListNode *newNode = new ListNode(val);
newNode->next = head;
head = newNode;
return;
}
ListNode *cur = head;
while (cur && pos > 1) {
cur = cur->next;
pos--;
}
if (cur) {
ListNode *newNode = new ListNode(val);
newNode->next = cur->next;
cur->next = newNode;
}
}
// 删除节点
void deleteNode(ListNode *&head, int pos) {
if (pos < 0) return;
if (pos == 0) {
ListNode *delNode = head;
head = head->next;
delete delNode;
return;
}
ListNode *cur = head;
while (cur && pos > 1) {
cur = cur->next;
pos--;
}
if (cur && cur->next) {
ListNode *delNode = cur->next;
cur->next = delNode->next;
delete delNode;
}
}
// 遍历链表
void traverseList(ListNode *head) {
while (head) {
cout << head->val << " ";
head = head->next;
}
cout << endl;
}
int main() {
int nums[] = {1, 2, 3, 4, 5};
int n = sizeof(nums) / sizeof(int);
ListNode *head = createList(nums, n);
traverseList(head);
insertNode(head, 2, 6);
traverseList(head);
deleteNode(head, 3);
traverseList(head);
return 0;
}
```
在上面的代码中,我们定义了一个 `ListNode` 结构体作为链表节点,包括节点值 `val` 和指向下一个节点的指针 `next`。同时,我们实现了创建链表、插入节点、删除节点和遍历链表等基本操作。在使用链表时,我们可以先通过 `createList` 函数创建一个链表,然后对链表进行插入、删除和遍历操作。
相关推荐
![](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)
![](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)