GeeksforGeeks » Algorithms
Linked List
(5 posts)-
Given a linked list as follows:
a->b->c->1->2->3
Arrange it in a manner it would return
a->1->b->2->c->3
Note:list contains even number of nodes. -
maintain two stack...
in stack1 keep on pushing the nodes until some node->data!=numeric value;
now push all numeric node in the stack2.n1=pop(stack2);
n2=pop(stack1);
n1->next=n2;keep on doing that until both stack are null
-
2nd method :
maintain one ptr1 at head.
increment ptr2 till it reaches a node which has numeric value...in the given example its "1";
now remove node at ptr2 and add it to the next of ptr1;
increment ptr1 twice. -
@atul007
increment ptr2 till it reaches a node which has numeric value...in the given example its "1";I think ptr2 should point to the node before 1( which is c), but not the 1. As we need to connect c and 2 after linking node 1 between a and b nodes.
lets ptr1 points to a
lets ptr2 points to c ( which is node before 1 )1> temp = ptr2->next->next ( save node after 1 which is 2 in temp)
insert 1 between a and b
2> ptr2->next->next = ptr1->next ( make 1's next, point to b)
3> ptr1->next = ptr2->next; ( make a's next, point to 1)connect c and 2
4> ptr2->next = temp; (make c's next, point to 2)5> ptr1 = ptr1->next->next; (lets ptr1 point to b)
Repeat steps from 1-6 until ptr1 reaches ptr2. Or ptr2->next reaches NULL.
Thanks.
-
#include<stdio.h> #include<stdlib.h> #include<ctype.h> typedef struct node { char data ; struct node *next ; }node ; node* createNode (char ch) { node *head ; head = (node *) malloc (sizeof(node)) ; head->data = ch ; head->next = NULL ; return head ; } node* getData () { int size, i ; char ch; node *head = NULL, *temp; printf ( "\nEnter the size of the string :\t " ) ; scanf ( "%d", &size ) ; for ( i = 0 ; i < size ; i ++ ) { printf ( "\nEnter the %d the character:\t",i+1 ) ; do { scanf ( "%c", &ch ); } while (!isalnum(ch)); if (head == NULL){ head = createNode (ch) ; temp = head ; } else { temp->next = createNode (ch) ; temp = temp->next ; } } return head ; } void printList (node *head) { node* list = head ; printf ( "\n\n" ) ; while (list) { printf ( "%c", list->data ) ; list = list->next ; } } node* performOperation (node* head) { node *ptr1, *temp, *ptr2 ; ptr2 = head ; while (ptr2->next) { if (isdigit(ptr2->next->data)) break ; ptr2 = ptr2->next ; } ptr1 = head ; while (ptr1) { temp = ptr2->next->next ; ptr2->next->next = ptr1->next ; ptr1->next = ptr2->next ; ptr2->next = temp ; ptr1 = ptr1->next->next ; } return head ; } int main() { node* head ; head = getData () ; printf ( "\nPrinting the list\n" ) ; printList (head); printf ( "\nBefore operation\n" ) ; head = performOperation (head) ; printf ( "\nAfter operation\n") ; printList (head); return 0 ; }
Reply
You must log in to post.