Add pset2

This commit is contained in:
juan 2022-03-14 19:54:02 +08:00
parent 5707659af0
commit 590bb4cd53
No known key found for this signature in database
GPG key ID: 5C1E5093C74F1DC7
2 changed files with 174 additions and 0 deletions

View file

@ -0,0 +1,76 @@
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *constructLinkedList();
Node *appendNode(Node *node, int data);
void deleteLinkedList(Node *head);
int main(void) {
Node *head = constructLinkedList();
int sum = 0, max, min;
max = head->data;
min = head->data;
while (head != NULL) {
if (head->data > max) {
max = head->data;
}
if (head->data < min) {
min = head->data;
}
sum += head->data;
head = head->next;
}
printf("The maximum,minmum and the total are:%d %d %d", max, min, sum);
deleteLinkedList(head);
return 0;
}
Node *constructLinkedList() {
int data;
scanf("%d", &data);
Node *head = malloc(sizeof(Node));
Node *ptr = head;
head->data = data;
head->next = NULL;
scanf("%d", &data);
while (data != -1) {
ptr = appendNode(ptr, data);
scanf("%d", &data);
}
return head;
}
Node *appendNode(Node *head, int data) {
Node *new = malloc(sizeof(Node));
new->data = data;
new->next = NULL;
head->next = new;
return new;
}
void deleteLinkedList(Node *head) {
if (head->next == NULL) {
free(head);
return;
} else {
deleteLinkedList(head->next);
free(head);
}
}

View file

@ -0,0 +1,98 @@
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
void swapNode(Node *a, Node *b);
void bubbleSort(Node *head);
Node *constructLinkedList();
Node *appendNode(Node *node, int data);
void deleteLinkedList(Node *head);
int main(void) {
Node *head = constructLinkedList();
bubbleSort(head);
printf("The new list is:");
Node *ptr = head;
while (ptr->next != NULL) {
printf("%d ", ptr->data);
ptr = ptr->next;
}
printf("%d", ptr->data);
deleteLinkedList(head);
return 0;
}
// Actually only swaps the data inside
void swapNode(Node *a, Node *b) {
int tmp = a->data;
a->data = b->data;
b->data = tmp;
}
void bubbleSort(Node *head) {
int swapped;
Node *ptr1;
Node *ptr2 = NULL;
if (head == NULL) {
return;
}
do {
swapped = 0;
ptr1 = head;
while (ptr1->next != ptr2) {
if (ptr1->data > ptr1->next->data) {
swapNode(ptr1, ptr1->next);
swapped = 1;
}
ptr1 = ptr1->next;
}
ptr2 = ptr1;
} while (swapped);
}
Node *constructLinkedList() {
int data;
scanf("%d", &data);
Node *head = malloc(sizeof(Node));
head->data = data;
head->next = NULL;
Node *ptr = head;
scanf("%d", &data);
while (data != -1) {
ptr = appendNode(ptr, data);
scanf("%d", &data);
}
return head;
}
Node *appendNode(Node *node, int data) {
Node *new = malloc(sizeof(Node));
new->data = data;
new->next = NULL;
node->next = new;
return new;
}
void deleteLinkedList(Node *head) {
if (head != NULL) {
deleteLinkedList(head->next);
free(head);
}
}