BUPT-homework/semester2/pset1/2-reverseLinkedList.c

97 lines
1.6 KiB
C
Raw Normal View History

2022-03-08 14:55:11 +08:00
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
struct Node *next;
struct Node *prev;
int data;
} Node;
// Returns the head of the linked list
Node *newLinkedList();
// Returns a pointer to the next node
Node *appendNode(Node *prev);
// Prints the linked list in reverse order
void printListReverse(Node *head);
// Frees the list from memory
void freeList(Node *head);
int main(void) {
// Get rows of input
int rows;
scanf("%d", &rows);
Node *head;
for (int i = 0; i < rows; i++) {
head = newLinkedList();
printListReverse(head);
freeList(head);
}
return 0;
}
Node *newLinkedList() {
Node *ptr, *head;
// Initialize head
head = malloc(sizeof(Node));
head->prev = NULL;
head->next = NULL;
ptr = head;
// Initialize list
int data;
scanf("%d", &data);
while (data != -1) {
ptr->data = data;
ptr = appendNode(ptr);
scanf("%d", &data);
}
return head;
}
Node *appendNode(Node *prev) {
Node *node;
node = malloc(sizeof(Node));
prev->next = node;
node->prev = prev;
node->next = NULL;
return node;
}
void printListReverse(Node *head) {
// Can't use recursion because the output should be formatted
Node *ptr = head;
while (ptr->next != NULL) {
ptr = ptr->next;
}
// ptr now points to the tail.
ptr = ptr->prev;
if (ptr != NULL) {
printf("%d", ptr->data);
ptr = ptr->prev;
}
while (ptr != NULL) {
printf(" %d", ptr->data);
ptr = ptr->prev;
}
printf("\n");
}
void freeList(Node *head) {
if (head->next != NULL) {
freeList(head->next);
free(head);
} else {
free(head);
}
}