#include <stdio.h> #include <stdlib.h> typedef struct Node { int data; /* Could
ID: 3554013 • Letter: #
Question
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data; /* Could put any kind of data here*/
struct Node *next; /* Self-referential requires "struct"*/
} Node;
/*/ Insert a new node as the second one on the list, if there is already a node, or
// as the only node on the list, otherwise.*/
Node *AddSecond(Node *head, int data) {
Node *temp;
temp = malloc(sizeof(Node));
temp-> data = data;
if(head==NULL) {
head = temp;
temp->next = head;
}
else {
head->next->next = temp;
if(temp->next == NULL)
temp->next = head;
}
return temp;
}
void PrintAll(char *tag, Node *head) {
Node *temp;
printf("%s:", tag);
for (temp = head; temp != NULL; temp = temp->next)
printf(" %d", temp->data);
printf(" ");
}
int main() {
Node *head = NULL;
head = AddSecond(head, 10);
head = AddSecond(head, 20);
head = AddSecond(head, 15);
head = AddSecond(head, 12);
PrintAll("After insert", head);
return 0;
}
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data; /* Could put any kind of data here*/
struct Node *next; /* Self-referential requires "struct"*/
} Node;
/*/ Insert a new node as the second one on the list, if there is already a node, or
// as the only node on the list, otherwise.*/
Node *AddSecond(Node *head, int data) {
Node *temp,*node;
temp = malloc(sizeof(Node));
temp-> data = data;
if(!head) { // if head is null store the pointer to node temp in head
head = temp;
temp->next = NULL;
}
else {
if(!head->next) node = NULL; // If there is no second node. node = NULL
else node = head->next; // else store the address of second node
head->next = temp; // insert the newly created temp node at second position
temp->next = node; // place all other nodes to the left of newly created node
}
return head;
}
void PrintAll(char *tag, Node *head) {
Node *temp;
printf("%s:", tag);
for (temp = head; temp != NULL; temp = temp->next)
printf(" %d", temp->data);
printf(" ");
}
int main() {
Node *head = NULL;
head = AddSecond(head, 10);
PrintAll("After insert", head);
head = AddSecond(head, 20);
PrintAll("After insert", head);
head = AddSecond(head, 15);
PrintAll("After insert", head);
head = AddSecond(head, 12);
PrintAll("After insert", head);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.