Here we are going to write a program to position even and odd nodes together. First we will create a linked list and then put all the even position nodes together then the odd position nodes together or vice-versa is also true.
Suppose,
Input - 1 => 2 => 3 => 4 => NULL
Output - 2 => 4 => 1 => 3 => NULL
OR
Output- 1 => 3 => 2 => 4 => NULL
Program to position even and odd nodes together-
C Code-
#include <stdio.h>
#include <malloc.h>
struct node{
int data;
struct node* next;
};
void create(struct node** head,int val){
struct node* temp=*head;
struct node* newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=val;
newnode->next=NULL;
if(*head==NULL){
*head=newnode;
return;
}
while(temp->next!=NULL){
temp=temp->next;
}
temp->next=newnode;
}
struct node* evod(struct node* head){
struct node* odd=head;
struct node* even=head->next;
struct node* evenfirst=even;
if(head==NULL){
return NULL;
}
while(1){
odd->next=even->next;
odd=even->next;
if(odd->next==NULL)
{
even->next=NULL;
odd->next=evenfirst;
break;
}
even->next=odd->next;
even=odd->next;
}
return head;
}
void display(struct node* head){
while(head!=NULL){
printf("%d => ",head->data);
head=head->next;
}
printf("NULL\n");
}
int main(){
struct node* head=NULL;
create(&head,1);
create(&head,2);
create(&head,3);
create(&head,4);
create(&head,5);
create(&head,6);
create(&head,7);
evenodd(&head);
display(head);
head=evod(head);
display(head);
return 0;
}Output-
1 => 2 => 3 => 4 => 5 => 6 => 7 => NULL
1 => 3 => 5 => 7 => 2 => 4 => 6 => NULL Time Complexity: O(n) where n is the length of the linked list.
Linked List Problems-
Post a Comment
If you have any doubts, please let me know