Description
Please complete PrintListAndFindMax(Node* head): Please print out all the values of the nodes first in their original order, with numbers separated by '->'. Then, find the maximum value inside and print it. This function does not need to return anything.
請完成 PrintListAndFindMax(Node* head):請先照原本順序印出所有節點的值,數字間用"->"隔開。接著找出裡面的最大值並印出,此函式不需進行回傳。
Input
The function "do not" require additional user input; everything needed will be directly provided as input!
"不需要"額外自己輸入值,要用到的都會直接作為參數傳入!
First line inputs an integer n, representing the number of nodes in the original linked list. Then, the second line consists of n numbers representing the values inside the linked list.
第一行輸入包含一個整數 n,代表原始 linked list 內的 node 個數。接下來第二行有 n 個數字,代表linked list內的值。
Output
Print all the values inside the linked list in thePrintListAndFindMaxfunction. Then, print out the maximum value among these numbers.
請在PrintListAndFindMax內印出所有linked list 內的值。接著印出這些數字中的最大值。
Sample Input 1
5
8 7 2 9 12
Sample Output 1
8->7->2->9->12
12
Base code givien below:
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node *next;
}Node;
void PrintListAndFindMax(Node* head){
}
/*
// 這段main請記得在上傳時刪除或註解掉
int main(){
int n, num1, num2;
int choice;
Node *head, *cur;
scanf("%d", &n);
cur = head;
for (int i=0;i<n;i++){// create list
// 創新的 Node
Node* new = (Node*)malloc(sizeof(Node));
scanf("%d", &(new->data));
new->next = NULL;
if (i == 0) // 一開始head為空
head = new; // 設為開頭的節點
else // 接到後面
cur->next = new;
cur = new;
}
PrintListAndFindMax(head);
return 0;
}
*/
ans:
#include <stdio.h>
#include <stdlib.h>
typedef struct node{
int data;
struct node *next;
} Node;
void PrintListAndFindMax(Node* head){
Node* current = head;
int max = head->data; // Initialize max with the data of the first node
// Traverse the linked list
while (current != NULL) {
// Print the value of the current node
printf("%d", current->data);
// Move to the next node if it exists
if (current->next != NULL) {
printf("->");
} else {
printf("\\n");
}
// Update max if the current node's data is greater
if (current->data > max) {
max = current->data;
}
current = current->next; // Move to the next node
}
// Print the maximum value found
printf("%d\\n", max);
}