我在尝试实现功能时遇到了麻烦,这是程序应该做的:用户必须首先输入一个整数(此数字不会添加到列表中)。然后,我必须编写一个函数,该函数以递归方式删除列表中所有输入数字倍数的节点。
这是我当前的代码:
#include <stdio.h>
#include <stdlib.h>
#define true 1
#define false 0
#define bool int
typedef struct node {
int data;
struct node *next;
} Node;
void addToHead(Node **head, int value);
void printList(Node *head);
bool isMultipleOf(int value, int n);
void deleteMultipleOfNNodes(Node **head, int n);
int main() {
// Create head
Node *head = NULL;
int loop = true;
int input;
// The value whose multiples must be deleted from the list
int n;
scanf("%d", &n);
while (loop) {
scanf("%d", &input);
// End loop - print list
if (input < 0) {
deleteMultipleOfNNodes(&head, n);
printList(head);
loop = false;
} else {
// Add value to the head
addToHead(&head, input);
}
}
return 0;
}
void addToHead(Node **head, int value) {
Node *temp;
if (*head != NULL) {
// Create new node
Node *newNode = (Node*) malloc(sizeof(Node));
// Set new node data
newNode -> data = value;
// New node links to the head
newNode -> next = *head;
// New node is now the head of the list
*head = newNode;
} else {
// Create head
*head = (Node*) malloc(sizeof(Node));
// Set head data
(*head) -> data = value;
// Head links to NULL
(*head) -> next = NULL;
}
}
void printList(Node *head) {
Node *temp = head;
while (temp != NULL) {
if (temp -> next != NULL) {
printf("%d -> ", temp->data);
} else {
printf("%d -> NULL", temp -> data);
}
temp = temp->next;
}
}
bool isMultipleOf(int value, int n) {
// While the value is greater than zero, keep on subtracting the number
while (value > 0) {
value -= n;
}
return (value == 0);
}
void deleteMultipleOfNNodes(Node **head, int n) {
// ========= CODE ================
}
谢谢您的帮助!
该功能看起来很简单
void deleteMultipleOfNNodes( Node **head, int n )
{
if ( Node *tmp = *head )
{
tmp->data % n == 0 ? ( *head ) = ( *head )->next, free( tmp )
: head = &( *head )->next;
deleteMultipleOfNNodes( head, n );
}
}