Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Create a Singly Linked List

Problem Statement:

Declare a struct of your choice (Employee, Student, etc). Declare a node for singly link list. Declare an ADT of this linklist. Then Write a function that takes two ADTs of sorted Link Lists and Merge

Plz! write a code for the given problem this is my assignment and his due date is today 12 Pm ..
by

2 Answers

Bharatgxwzm
Execution of this calculation is given beneath ?
#include <stdio.h>
#include <stdlib.h>

struct node {
int data;
struct node next;
};

struct node *head = NULL;
struct node *current = NULL;

//display the list
void printList() {

struct node *ptr = head;

printf("\n[head] =>");
//start from the beginning
while(ptr != NULL) {
printf(" %d =>",ptr->data);
ptr = ptr->next;
}

printf(" [null]\n");
}

//insert link at the first location
void insert(int data) {
//create a link
struct node *link = (struct node
) malloc(sizeof(struct node));

//link->key = key;
link->data = data;

//point it to old first node
link->next = head;

//point first to new first node
head = link;
}

int main() {
insert(10);
insert(20);
insert(30);
insert(1);
insert(40);
insert(56);

printList();
return 0;
}


Output of the program should be ?

[head] => 56 => 40 => 1 => 30 => 20 => 10 => [null]
Shahlar1vxp
In order to create a singly linked list, you should not incrtement head after 'head = head-> next' in the for loop otheriwse the printlist returns NULL each time as the loop will not stop until and unless the 'head' is NULL. You may use the code-
LIST current = head;
while (current != NULL) {
printf("%s %d", current->str, current->count);
current = current->next;
}

You need to remember that the second malloc allocates memory but the return value for it is not assigned to anything so that the allocated memory gets lost. A *newList* is allocated but is not initialized. So using a *memcpy* for copying memory to *newList
->str fails since newList ->str points to nothing.

Login / Signup to Answer the Question.