Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

Lab Report

On
A program that will take a defined singly link list
and insert a new value in the list
COURSE CODE: CSE 232
Course Title: Data Structures Lab
Experiment No - 03

Submitted To: Submitted By:


Sadah Anjum Shanto Romzan Ali Mohon

Lecturer Id: 17182103178


Intake: 38
Dept. of CSE Section: 4

DEPARTM ENT OF CO M PUTER SCIENCE AND ENG INEERING


BANGLA DESH UNIVERSITY OF BUSINESS AND TECHNOLOGY

Submission Date: 06.05.2019


Source code:

#include<stdio.h>
#include<stdlib.h>

typedef struct mylist


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

void insert(node* s, int data)


{
while(s->next != NULL)
{
s = s->next;
}
s->next = (node*)malloc(sizeof(node));
s->next->data = data;
s->next->next = NULL;
}

void display(node *s)


{
while(s->next != NULL)
{
printf("%d\n",s->next->data);
s = s->next;
}
}

node* getNode(int data)


{
node* newNode = (node*)malloc(sizeof(node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}

void insertAtMid(node** head_ref, int x)


{
if (*head_ref == NULL)
*head_ref = getNode(x);
else {
node* newNode = getNode(x);
node* ptr = *head_ref;
int len = 0;
while (ptr != NULL) {
len++;
ptr = ptr->next;
}
int count = ((len % 2) == 0) ? (len / 2) :
(len + 1) / 2;
ptr = *head_ref;
while (count-- > 1)
ptr = ptr->next;
newNode->next = ptr->next;
ptr->next = newNode;
}
}

int main()
{
node* first = (node*)malloc(sizeof(node));
first->next = NULL;
insert(first, 1);
insert(first, 2);
insert(first, 3);
insert(first, 4);
insert(first, 5);
display(first);
printf("after inserting a value: \n");
insertAtMid(first,7);
display(first);

You might also like