New semester!

This commit is contained in:
juan 2022-03-08 14:55:11 +08:00
parent 5dee97aa6e
commit d85fc37aca
No known key found for this signature in database
GPG key ID: 5C1E5093C74F1DC7
3 changed files with 168 additions and 0 deletions

View file

@ -0,0 +1,67 @@
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *appendNode(Node *n) {
int data;
scanf("%d", &data);
Node *node = malloc(sizeof(struct Node));
node->data = data;
node->next = NULL;
n->next = node;
return node;
}
Node *makeList(int col) {
Node *head, *ptr;
head = malloc(sizeof(Node));
head->next = NULL;
ptr = head;
for (int i = 0; i < col; i++) {
ptr = appendNode(ptr);
}
return head;
}
void delete(Node *head) {
if (head->next == NULL) {
free(head);
} else {
delete(head->next);
}
}
int main(void) {
int rows;
int col;
int count;
scanf("%d", &rows);
Node *ptr;
for (int i = 0; i < rows; i++) {
scanf("%d", &col);
Node *head = makeList(col);
count = 0;
for (ptr = head->next; ptr != NULL; ptr = ptr->next) {
if (count % 2 == 1) {
if (count == 1) {
printf("%d", ptr->data);
} else {
printf(" %d", ptr->data);
}
}
count++;
}
printf("\n");
delete(head);
}
return 0;
}

View file

@ -0,0 +1,96 @@
#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);
}
}

View file

@ -0,0 +1,5 @@
# Pset 1
## Info
the problem set can be found [here](https://pintia.cn/problem-sets/1499923457155141632)