Last active
February 2, 2019 14:43
-
-
Save awadhawan18/2fb584f8fd26b036cb925312f09ac03f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
#include<bits/stdc++.h> | |
using namespace std; | |
/* Link list node */ | |
struct node *reverse (struct node *head, int k); | |
struct node | |
{ | |
int data; | |
struct node* next; | |
}*head; | |
/* UTILITY FUNCTIONS */ | |
/* Function to push a node */ | |
void insert() | |
{ | |
int n,value; | |
cin>>n; | |
struct node *temp; | |
for(int i=0;i<n;i++) | |
{ | |
cin>>value; | |
if(i==0) | |
{ | |
head=(struct node *) malloc( sizeof(struct node) ); | |
head->data=value; | |
head->next=NULL; | |
temp=head; | |
continue; | |
} | |
else | |
{ | |
temp->next= (struct node *) malloc( sizeof(struct node) ); | |
temp=temp->next; | |
temp->data=value; | |
temp->next=NULL; | |
} | |
} | |
} | |
/* Function to print linked list */ | |
void printList(struct node *node) | |
{ | |
while (node != NULL) | |
{ | |
printf("%d ", node->data); | |
node = node->next; | |
} | |
printf(" | |
"); | |
} | |
/* Drier program to test above function*/ | |
int main(void) | |
{ | |
/* Start with the empty list */ | |
int t,k,value,n; | |
/* Created Linked list is 1->2->3->4->5->6->7->8->9 */ | |
cin>>t; | |
while(t--) | |
{ | |
insert(); | |
cin>>k; | |
head = reverse(head, k); | |
printList(head); | |
} | |
return(0); | |
} | |
} | |
struct node *reverseIt(struct node *head, int k){ | |
struct node *temp = head; | |
struct node *prev = head; | |
struct node *front = head->next; | |
while(k-- && front!=NULL && head!=NULL){ | |
temp = front; | |
front = temp->next; | |
temp->next = prev; | |
prev = temp; | |
} | |
head->next = front; | |
return temp; | |
} | |
struct node *reverse (struct node *head, int k) | |
{ | |
struct node *temp = head; | |
struct node *newHead = reverseIt(head,k-1); | |
temp = head; | |
head = head->next; | |
while(head!=NULL){ | |
temp->next = reverseIt(head, k-1); | |
temp = head; | |
head = head->next; | |
} | |
return newHead; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment