双链表练习
#include <stdio.h> #include <stdlib.h> typedef struct intnode { int data; struct intnode* prev; struct intnode* next; } node; void swap(node* ptr1, node* ptr2) { ptr1->prev->next = ptr2; if (ptr2->next != NULL) { ptr2->next->prev = ptr1;//要考虑ptr2->next是否为空 } ptr1->next = ptr2->next; ptr2->next = ptr1; ptr2->prev = ptr1->prev; ptr1->prev = ptr2; } int main() { int n; scanf("%d", &n); int* num = (int*)malloc(n * sizeof(int)); for (int i = 0; i < n; i++) { scanf("%d", &num[i]); } node* head = (node*)malloc(sizeof(node)); node* tmp = head; for (int i = 0; i < n; i++) { node* ptr = (node*)malloc(sizeof(node)); ptr->data = num[i]; ptr->next = NULL; ptr->prev = tmp; tmp->next = ptr; tmp = tmp->next; } if (n > 1) { swap(head->next, head->next->next); swap(tmp->prev, tmp); } tmp = head; for (int i = 0; i < n; i++) { tmp = tmp->next; free(tmp->prev); tmp->prev = NULL; printf("%d ", tmp->data); } return 0; }