Week - 4
Week - 4
#include <stdio.h>
#include <stdlib.h>
struct node
{
int value;
struct node* next;
};
struct node* head;
struct node* node_new(int val)
{
struct node* newnode = (struct node*)malloc(sizeof(struct node));
newnode->value = val;
newnode->next = NULL;
return newnode;
}
void insertAtEnd(int val)
{
struct node* newnode = node_new(val);
if(head==NULL)
{
head=newnode;
}
else{
struct node* current = head;
while(current->next!=NULL)
{
current = current->next;
}
current->next = newnode;
}
}
void print()
{
struct node* temp = head;
while(temp!=NULL){
printf("%d ",temp->value);
temp=temp->next;
}
printf("\n");
}
int main()
{
head=NULL;
int n;
scanf("%d",&n);
for(int i=0 ; i<n ; i++){
int value;
scanf("%d",&value);
insertAtEnd(value);
}
print();
}
In-Lab – 2(page No: 73)
typedef struct Node NODE;
NODE *getMiddleElement(NODE *head)
{
if (head == NULL)
{
return NULL; // Return NULL if the list is empty
}
struct Node *temp=head,*pretemp=head;
while(temp !=NULL && temp->next != NULL)
{
pretemp=pretemp->next;
temp=temp->next->next;
}
return pretemp;
}
In-Lab – 3(page No: 75)
void insertAfterK(LinkedList* list, int value, int k)
{
Node* newNode = createNode(value);
Node* current = list->head;
if (current == NULL)
{
list->head = newNode;
return;
}
for (int i = 1; i < k; i++) {
current = current->next;
}
newNode->next=current->next;
current->next=newNode;
}
Post-Lab – 1(page No: 77)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n)
{
struct ListNode *temp=head,*pre;
int count=0,i=1;
while(temp!=NULL)
{
count++;
temp=temp->next;
}
if(count<=1) return NULL;
if(count==n) return head->next;
temp=head;
for(i=1;i<(count-n);i++)
{
temp=temp->next;
}
temp->next=temp->next->next;
return head;
}
/*struct node
{
int data;
struct node* next;
};*/
free(evenDummyHead);
free(oddDummyHead);
return rearrangedHead;
}
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2)
{
struct ListNode* temp = (struct ListNode*)malloc(sizeof(struct ListNode));
temp->val = 0;
temp->next = NULL;
struct ListNode* current = temp;
while (list1 != NULL && list2 != NULL)
{
if (list1->val <= list2->val)
{
current->next = list1;
list1 = list1->next;
}
else
{
current->next = list2;
list2 = list2->next;
}
current = current->next;
}
if (list1 != NULL)
{
current->next = list1;
}
else
{
current->next = list2;
}
return temp->next;
}