What is the output of the following code: [code] #include<stdio.h> #include<stdlib.h> struct Node { int val; struct Node* next; }*head

Giao Linh

New member
What is the output of the following code:
Code:
#include<stdio.h>
#include<stdlib.h>
struct Node
{
     int val;
     struct Node* next;
}*head;
int get_max()
{
      struct Node* temp = head->next;
	  int max_num = temp->val;
	  while(temp != 0)
	  {
	        if(temp->val > max_num)
		    max_num = temp->val;
		temp = head->next;
	  }
	  return max_num;
}
int main()
{
      int n = 9, arr[9] ={5,1,3,4,5,2,3,3,1},i;
      struct Node *temp, *newNode;
      head = (struct Node*)malloc(sizeof(struct Node));
      head -> next =0;
      temp = head;
      for(i=0;i<n;i++)
      {
          newNode =(struct Node*)malloc(sizeof(struct Node));
          newNode->next = 0;
          newNode->val = arr[i];
          temp->next =newNode;
          temp = temp->next;
      }
      int max_num = get_max();
      printf("%d %d",max_num);
      return 0;
}
A. 5
B. 1
C. runtime error
D. garbage value
 
Answer: C
Explanation: The variable temp will always point to the first element in the linked list due to the line “temp = head->next” in the while loop. So, it will be an infinite while loop and the program will produce a runtime error.
 

Tìm kiếm

Back
Top