text: Alternate Odd and Even Nodes in a Singly Linked List | C # program to rearrange nodes as alternate odd even nodes in a Singly Linked List ; class node ; A utility function to print linked list ; Function to create newNode in a linkedlist ; Function to insert at beginning ; Function to rearrange the odd and even nodes ; Odd Value in Even Position Add pointer to current node in odd stack ; Even Value in Odd Position Add pointer to current node in even stack ; Swap Data at the top of two stacks ; Driver code
code: using System ; using System . Collections . Generic ; class GFG { public class Node { public int data ; public Node next ; } static void printList ( Node node ) { while ( node != null ) { Console . Write ( node . data + " ▁ " ) ; node = node . next ; } Console . WriteLine ( ) ; } static Node newNode ( int key ) { Node temp = new Node ( ) ; temp . data = key ; temp . next = null ; return temp ; } static Node insertBeg ( Node head , int val ) { Node temp = newNode ( val ) ; temp . next = head ; head = temp ; return head ; } static void rearrangeOddEven ( Node head ) { Stack < Node > odd = new Stack < Node > ( ) ; Stack < Node > even = new Stack < Node > ( ) ; int i = 1 ; while ( head != null ) { if ( head . data % 2 != 0 && i % 2 == 0 ) { odd . Push ( head ) ; } else if ( head . data % 2 == 0 && i % 2 != 0 ) { even . Push ( head ) ; } head = head . next ; i ++ ; } while ( odd . Count > 0 && even . Count > 0 ) { int k = odd . Peek ( ) . data ; odd . Peek ( ) . data = even . Peek ( ) . data ; even . Peek ( ) . data = k ; odd . Pop ( ) ; even . Pop ( ) ; } } public static void Main ( String [ ] args ) { Node head = newNode ( 8 ) ; head = insertBeg ( head , 7 ) ; head = insertBeg ( head , 6 ) ; head = insertBeg ( head , 5 ) ; head = insertBeg ( head , 3 ) ; head = insertBeg ( head , 2 ) ; head = insertBeg ( head , 1 ) ; Console . WriteLine ( " Linked ▁ List : " ) ; printList ( head ) ; rearrangeOddEven ( head ) ; Console . WriteLine ( " Linked ▁ List ▁ after ▁ " + " Rearranging : " ) ; printList ( head ) ; } }