LAB 5 Use this struct for questions: struct node { int struct node*
data; next;
};
Q-1) Write a function called Length(struct node* head) to calculate the length of the given list. Return type is integer. (4 points) Q-2) Write a function called append(struct node** head, int number). It should add a new node at the end of the list. (3 points) Q-3) Write a function called push(struct node** head, int number). It should add a new node at the beginning of a list. (3 points) Bonus) Write a function called createList(int numberOfNodes) to automatize the creation of a linked list. If we call the function like createList(5) it should create 5 noded list automatically: (3 points – you can choose this question instead of Q-2 or Q-3)
LAB 5 Solutions A-1) int Length(struct node* head) { struct node* current = head; int count = 0; while (current != NULL) { count++; current = current->next; } return count; }
A-2) struct node* AppendNode(struct node** headRef, int num) { struct node* current = *headRef; struct node* newNode; newNode = malloc(sizeof(struct node)); newNode->data = num; newNode->next = NULL; // special case for length 0 if (current == NULL) { *headRef = newNode; } else { // Locate the last node while (current->next != NULL) { current = current->next; } current->next = newNode; } }
A-3) void Push(struct node** headRef, int data) { struct node* newNode = malloc(sizeof(struct node)); newNode->data = data; newNode->next = *headRef; // The '*' to dereferences back to the real head *headRef = newNode; // ditto }
Bonus) Fonksiyon haline getirmedim fakat Ĺ&#x;una bakabilirsiniz: #include<stdlib.h> #include<stdio.h> struct list_el { int val; struct list_el * next; }; typedef struct list_el item; void main() { item * curr, * head; int i;
head = NULL; for(i=1;i<=10;i++) { curr = (item *)malloc(sizeof(item)); curr->val = i; curr->next = head; head = curr; } curr = head; while(curr) { printf("%d\n", curr->val); curr = curr->next ; } }