已知线性表采用带头结点的单链表存储结构。编写程序:在带头结点的l1中删除在l2中存在的元素,已知线性表采用带头结点的单链表存储结构。编写c语言程序:在带头结点的l1中删除在l2中存在的元素,
时间: 2024-05-04 17:15:51 浏览: 89
数据结构C语言版-线性表的单链表存储结构表示和实现.doc
这是一个关于编程的问题,我可以回答。下面是一个示例C语言程序:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
void delete_common(Node *l1, Node *l2) {
Node *p = l1->next;
Node *pre = l1;
while (p) {
Node *q = l2->next;
int found = 0;
while (q) {
if (p->data == q->data) {
found = 1;
break;
}
q = q->next;
}
if (found) {
pre->next = p->next;
free(p);
p = pre->next;
} else {
pre = p;
p = p->next;
}
}
}
int main() {
Node *l1 = (Node *)malloc(sizeof(Node));
l1->next = NULL;
Node *l2 = (Node *)malloc(sizeof(Node));
l2->next = NULL;
Node *p = l1;
for (int i = 1; i <= 10; ++i) {
Node *node = (Node *)malloc(sizeof(Node));
node->data = i;
node->next = NULL;
p->next = node;
p = p->next;
}
p = l2;
for (int i = 5; i <= 15; ++i) {
Node *node = (Node *)malloc(sizeof(Node));
node->data = i;
node->next = NULL;
p->next = node;
p = p->next;
}
printf("Before delete_common:\n");
p = l1->next;
while (p) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
delete_common(l1, l2);
printf("After delete_common:\n");
p = l1->next;
while (p) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
return 0;
}
```
这个程序实现了在带头结点的l1中删除在l2中存在的元素的功能。具体来说,它遍历l1中的每个元素,然后在l2中查找是否存在相同的元素。如果存在,则在l1中删除该元素。最后,程序输出删除前和删除后的l1中的元素,以验证程序的正确性。
阅读全文