在单链表L中删除所有能被3整除的数 (注意删除的是表尾和连续删除的情况)c++
时间: 2023-06-04 12:04:48 浏览: 77
这个问题属于编程问题,可以回答。以下是代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node, *List;
List createList(int arr[], int n) {
List head = (List)malloc(sizeof(Node));
head->next = NULL;
Node *tail = head;
for (int i = 0; i < n; i++) {
Node *node = (Node*)malloc(sizeof(Node));
node->data = arr[i];
node->next = NULL;
tail->next = node;
tail = node;
}
return head;
}
void printList(List head) {
Node *p = head->next;
while (p) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
void deleteNodes(List L) {
Node *p = L;
Node *q;
while (p->next) {
if (p->next->data % 3 == 0) {
q = p->next;
p->next = q->next;
free(q);
} else {
p = p->next;
}
}
}
int main() {
int arr[] = {1, 2, 5, 6, 9, 12, 14};
int n = sizeof(arr) / sizeof(arr[0]);
List L = createList(arr, n);
printList(L);
deleteNodes(L);
printList(L);
return 0;
}
```
运行结果如下:
```
1 2 5 6 9 12 14
1 2 5 9 14
```