用C++写出链表的创建,头插法,插入删除
时间: 2023-05-13 16:07:11 浏览: 89
链表的创建:
```
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* createList(int arr[], int n) {
ListNode* dummyHead = new ListNode(0);
ListNode* cur = dummyHead;
for (int i = 0; i < n; i++) {
cur->next = new ListNode(arr[i]);
cur = cur->next;
}
return dummyHead->next;
}
```
头插法:
```
ListNode* reverseList(ListNode* head) {
ListNode* dummyHead = new ListNode(0);
while (head != NULL) {
ListNode* next = head->next;
head->next = dummyHead->next;
dummyHead->next = head;
head = next;
}
return dummyHead->next;
}
```
插入删除:
```
void insertNode(ListNode* head, int val) {
ListNode* newNode = new ListNode(val);
newNode->next = head->next;
head->next = newNode;
}
void deleteNode(ListNode* head, int val) {
ListNode* prev = head;
ListNode* cur = head->next;
while (cur != NULL) {
if (cur->val == val) {
prev->next = cur->next;
delete cur;
break;
}
prev = cur;
cur = cur->next;
}
}
```