用c++写出链表的遍历,增加,删除,修改
时间: 2024-05-10 12:20:52 浏览: 44
c++链表的创建,插入和删除
链表遍历:
```c
void traverseList(struct Node* head) {
struct Node* current = head;
while(current != NULL) {
printf("%d ", current->data);
current = current->next;
}
}
```
链表增加:
```c
void insertNode(struct Node** head, int data) {
struct Node* newNode = (struct Node*) malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = *head;
*head = newNode;
}
```
链表删除:
```c
void deleteNode(struct Node** head, int data) {
struct Node* current = *head;
struct Node* previous = NULL;
if(current != NULL && current->data == data) {
*head = current->next;
free(current);
return;
}
while(current != NULL && current->data != data) {
previous = current;
current = current->next;
}
if(current == NULL) {
return;
}
previous->next = current->next;
free(current);
}
```
链表修改:
```c
void modifyNode(struct Node* head, int oldData, int newData) {
struct Node* current = head;
while(current != NULL) {
if(current->data == oldData) {
current->data = newData;
return;
}
current = current->next;
}
}
```
阅读全文