请给我一个完整的可交互的链表代码
时间: 2023-04-07 21:03:47 浏览: 54
以下是一个简单的可交互的链表代码:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void printList(struct Node* n) {
while (n != NULL) {
printf("%d ", n->data);
n = n->next;
}
}
void insertNode(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
int main() {
struct Node* head = NULL;
int choice, data;
do {
printf("\n1. Insert a node");
printf("\n2. Print the list");
printf("\n3. Exit");
printf("\nEnter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("\nEnter the data: ");
scanf("%d", &data);
insertNode(&head, data);
break;
case 2:
printf("\nThe list is: ");
printList(head);
break;
case 3:
printf("\nExiting...");
exit(0);
default:
printf("\nInvalid choice!");
}
} while (choice != 3);
return 0;
}