双向链表的C语言写法
- User
双向链表的C语言写法
- Assistant
#include <stdio.h> #include <stdlib.h>
struct node { int data; struct node *prev; struct node *next; };
struct node *createList(int n); void displayList(struct node *head); void insertAtBeginning(struct node **head, int data); void insertAtEnd(struct node **head, int data); void insertAtN(struct node **head, int data, int position); void deleteAtBeginning(struct node **head); void deleteAtEnd(struct node **head); void deleteAtN(struct node **head, int position);
int main() { int n, data, choice, position; struct node *head = NULL;
codeprintf("Enter the number of nodes: "); scanf("%d", &n); head = createList(n); if(head == NULL) { printf("Memory allocation failed!\n"); return 0; } displayList(head); while(1) { printf("\nSelect the operation to perform:\n"); printf("1. Insert at the beginning\n2. Insert at the end\n3. Insert at a position\n"); printf("4. Delete from the beginning\n5. Delete from the end\n6. Delete from a position\n"); printf("7. Display the list\n8. Exit\n"); printf("Enter your choice: "); scanf("%d", &choice); switch(choice) { case 1: printf("Enter the data to insert: "); scanf("%d", &data); insertAtBeginning(&head, data); displayList(head); break; case 2: printf("Enter the data to insert: "); scanf("%d", &data); insertAtEnd(&head, data); displayList(head); break; case 3: printf("Enter the data to insert: "); scanf("%d", &data); printf("Enter the position to insert at: "); scanf("%d", &position); insertAtN(&head, data, position); displayList(head); break; case 4: deleteAtBeginning(&head); displayList(head); break; case 5: deleteAtEnd(&head); displayList(head); break; case 6: printf("Enter the position to delete from: "); scanf("%d", &position); deleteAtN(&head, position); displayList(head); break; case 7: displayList(head); break; case 8: exit(0); default: printf("Invalid choice!\n"); break; } } return 0;