#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* createNode(int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode != NULL) {
newNode->data = value;
newNode->next = NULL;
}
return newNode;
}
void reverseList(Node** head) {
Node* prev = NULL;
Node* current = *head;
Node* next = NULL;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head = prev;
}
void printList(Node* head) {
Node* current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
Node* head = NULL;
int values[] = {1, 2, 3, 4, 5};
int numValues = sizeof(values) / sizeof(values[0]);
for (int i = numValues - 1; i >= 0; --i) {
Node* newNode = createNode(values[i]);
newNode->next = head;
head = newNode;
}
printf("翻转前: ");
printList(head);
reverseList(&head);
printf("翻转后: ");
printList(head);
return 0;
}
数据结构第二天作业
最新推荐文章于 2024-10-31 19:10:01 发布