IN C PROGRAMMING. how do i re-implement this using dummy nodes?? doing something
ID: 3886274 • Letter: I
Question
IN C PROGRAMMING.
how do i re-implement this using dummy nodes??
doing something with the listed below before the code
typedef struct nodestruct {
Key item;
struct nodestruct *next; }
Node;
typedef struct {
int size; // Number of items on user’s list
Node *head, *tail;
} List;
typedef struct linkedlist {
Node *head, *tail;
} List;
below is the code i already have
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
struct Node *empty_list(){
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
return new_node;
}
int size(struct Node *head) {
int count = 0;
while(head != NULL) {
count++;
head = head->next;
}
return count;
}
int kthItem(struct Node *head, int k) {
int N = size(head);
if(N < k) {
printf("Less number of node ");
return 0;
}
int i = 0;
while(i < k) {
head = head->next;
}
return head->data;
}
int checkItem(struct Node *head, int item) {
while(head != NULL){
if(head->data == item)
return 1;
}
return 0;
}
void deleteList(struct Node **head) {
struct Node *t = NULL;
struct Node *temp = *head;
while(temp != NULL) {
t = temp;
temp = temp->next;
free(t);
}
}
Explanation / Answer
struct Node
{
int data;
struct Node* next;
};
/* Given a reference (pointer to pointer) to the head
of a list and an int, push a new node on the front
of the list. */
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node =
(struct Node*) malloc(sizeof(struct Node));
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
/* Takes head pointer of the linked list and index
as arguments and return data at index*/
int GetNth(struct Node* head, int index)
{
struct Node* current = head;
int count = 0; /* the index of the node we're currently
looking at */
while (current != NULL)
{
if (count == index)
return(current->data);
count++;
current = current->next;
}
/* if we get to this line, the caller was asking
for a non-existent element so we assert fail */
assert(0);
}
/* Drier program to test above function*/
int main()
{
/* Start with the empty list */
struct Node* head = NULL;
/* Use push() to construct below list
1->12->1->4->1 */
push(&head, 1);
push(&head, 4);
push(&head, 1);
push(&head, 12);
push(&head, 1);
/* Check the count function */
printf("Element at index 3 is %d", GetNth(head, 3));
getchar();