complete the pset

This commit is contained in:
juan 2022-03-08 20:36:51 +08:00
parent d85fc37aca
commit 5707659af0
No known key found for this signature in database
GPG key ID: 5C1E5093C74F1DC7
2 changed files with 162 additions and 0 deletions

View file

@ -0,0 +1,60 @@
#include <stdio.h>
#include <stdlib.h>
typedef struct link {
int data;
struct link *next;
} * Link;
Link AppendNode(Link head, int data);
void DisplyNode(Link head);
int main() {
int data;
Link head = NULL;
while (1) {
scanf("%d", &data);
if (data == -1)
break;
head = AppendNode(head, data);
}
if (head != NULL)
DisplyNode(head);
else
printf("NULL");
return 0;
}
/*在此实现 AppendNode函数 */
Link AppendNode(Link head, int data) {
if (head == NULL) {
head = malloc(sizeof(Link));
head->next = NULL;
head->data = data;
} else {
Link ptr = head;
while (ptr->next != NULL) {
ptr = ptr->next;
}
Link next = malloc(sizeof(Link));
ptr->next = next;
next->next = NULL;
next->data = data;
}
return head;
}
/*在此实现DisplyNode函数 */
void DisplyNode(Link head) {
printf("%d", head->data);
Link ptr = head->next;
while (ptr != NULL) {
printf(",%d", ptr->data);
ptr = ptr->next;
}
}

102
semester2/pset1/4-Joseph.c Normal file
View file

@ -0,0 +1,102 @@
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
// Clockwise order
struct Node *next;
// Anti clockwise order
struct Node *prev;
// Starts from 1, clockwise
int id;
} Node;
Node *constructRing(int len);
Node *appendNode(Node *head, int id);
Node *deleteNode(Node *head, int direction);
Node *iterateNode(Node *head, int direction,
int count); // 1: clockwise, 0: anti clockwise
int main(void) {
int n, m, k;
scanf("%d%d%d", &n, &m, &k);
Node *head = constructRing(n);
int count = 0;
for (int i = 0; i < n; i++) {
// determine the count
if (i % 2 == 0) { // Anti clockwise
count = m;
} else {
count = k;
}
head = iterateNode(head, i % 2, count);
printf("%d ", head->id);
head = deleteNode(head, i % 2);
}
return 0;
}
Node *constructRing(int len) {
// Construct the first node
Node *head = malloc(sizeof(Node));
head->id = 1;
head->prev = NULL;
head->next = NULL;
Node *ptr = head;
for (int i = 2; i <= len; i++) {
ptr = appendNode(ptr, i);
}
ptr->next = head;
head->prev = ptr;
return head;
}
Node *appendNode(Node *head, int id) {
Node *new = malloc(sizeof(Node));
new->id = id;
new->prev = head;
new->next = NULL; // Can be deleted
head->next = new;
return new;
}
Node *deleteNode(Node *head, int direction) {
Node *prev = head->prev;
Node *next = head->next;
if (head == next) {// Single element in the ring
free(head);
return NULL;
}
prev->next = next;
next->prev = prev;
free(head);
if (direction == 1)
return next;
else
return prev;
}
Node *iterateNode(Node *head, int direction,
int count) { // 1: clockwise, 0: anti clockwise
Node *ptr = head;
for (int i = 1; i < count; i++) { // starts from 1
if (direction == 1)
ptr = ptr->next;
else
ptr = ptr->prev;
}
return ptr;
}