typedef struct Node {
int data;
struct Node* next;
} Node;
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
printf("内存分配失败\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void appendNodes(Node** head, int* dataArray, int count) {
Node* tail = NULL;
Node* current = *head;
for (int i = 0; i < count; i++) {
Node* newNode = createNode(dataArray[i]);
if (*head == NULL) {
*head = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
}
void printList(Node* head) {
Node* current = head;
while (current != NULL) {
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}
void freeList(Node* head) {
Node* current = head;
Node* nextNode;
while (current != NULL) {
nextNode = current->next;
free(current);
current = nextNode;
}
}
int differCollection(Node* L1, Node* L2, Node* L3) {
Node *p1 = L1, *p2 = L2;
Node *p3 = L3;
Node *tail = L3;
int count = 0;
while(p1 && p2) {
if(p1->data < p2->data){
tail->next = p1;
tail = p1;
count++;
p1 = p1->next;
}else if(p1->data > p2->data){
p2 = p2->next;
}else {
p1 = p1->next;
p2 = p2->next;
}
}
while(p1) {
tail->next = p1;
tail=p1;
count++;
p1 = p1->next;
}
return count;
}
void delMin(Node* h) {
Node *pre = h->next;
Node *p = pre->next;
Node *minp = h->next;
Node *minpre = h;
while(p != NULL) {
if(p->data < minp->data){
minp = p;
minpre = pre;
}
pre = p;
p = p->next;
}
minpre->next = minp->next;
free(minp);
}
void delX(Node *h, int x){
Node *p = h->next;
Node *pre = h;
Node *temp;
while(p != NULL) {
if(p->data == x) {
temp = p;
pre->next = p->next;
p = p->next;
free(temp);
}else{
pre = p;
p = p->next;
}
}
}
void delX2(Node *h, int x){
Node *p = h->next;
Node *head = p;
Node *tail = p;
while(p!=NULL){
if(p->data != x){
tail->next = p;
tail = p;
}
p=p->next;
}
}
int main() {
Node* head1 = NULL;
int dataArray1[] = {2, 3, 2, 1, 2, 11, 23};
int count1 = sizeof(dataArray1) / sizeof(dataArray1[0]);
Node* head2 = NULL;
int dataArray2[] = {1, 2, 3, 4, 6, 9, 12};
int count2 = sizeof(dataArray2) / sizeof(dataArray2[0]);
appendNodes(&head1, dataArray1, count1);
appendNodes(&head2, dataArray2, count2);
Node* head3 = (Node*)malloc(sizeof(Node));
int count = differCollection(head1, head2, head3);
printf("个数%d\n", count);
printList(head1);
delMin(head1);
printList(head1);
delX2(head1, 2);
printList(head1);
return 0;
}