public static ListNode ReverseAlternate(ListNode head, int k) { var current = head; ListNode previous = null; while (current != null) { int count = 0; ListNode next = ReverseKElement.ReverseSub(current, k); if (previous == null) { //if previous is still null then p is the head node //assign the new head to the output of reverseSub head = next; } else { previous.next = next; } //Move k Steps while (current != null && count < k + 1) { //keep track of the previous value previous = current; current = current.next; count++; } } return(head); }
/// <summary> /// Reserve the linked list in group of k (HARD) /// </summary> public static ListNode ReverseNodeInGroupK(ListNode head, int k) { var current = head; ListNode previous = null; while (current != null) { ListNode next = ReverseKElement.ReverseSub(current, k); if (previous == null) { //if previous is still null then p is the head node //assign the new head to the output of reverseSub head = next; } else { previous.next = next; } //keep track of the previous value previous = current; current = current.next; } return(head); }