Answers for "reverse linked list by k"

C++
1

reverse linked list by k

//Iterative program in C++ to reverse a linked list in groups of k

//	(just before end of 2nd iteration of outer loop) [ 1->2->3->4->5->NULL ]
// 1 <- 2    3 <- 4  5 ->NULL   (k=2)
   ^		 ^		 ^
   |		 |		 |
prev_tail temp_head walker

void reverse_by_k(Node **head,int k){
    Node* temp_head = *head,*walker = *head,*prev_tail = NULL;
    while(walker){
        int i=0;
        Node *temp = NULL,*prev = NULL;
        //initialize temporary head to set previous tail later
        temp_head = walker;
        
        //reverse group of k nodes
        while(i<k && walker){
            temp = walker->next;
            walker->next = prev;
            prev = walker;
            walker = temp;
            i++;
        }
        
        if(prev_tail){
            //previous tail has to point to temporary head of current group
            prev_tail->next = prev;
            prev_tail = temp_head;
        } else{
            prev_tail = *head;
            *head = prev;
        }
    }
}
Posted by: Guest on September-20-2021
6

reverse a linked list

class recursion { 
	static Node head; // head of list 
	static class Node { 
		int data; 
		Node next; 
		Node(int d) 
		{   data = d; 
			next = null; 	} } 
	static Node reverse(Node head) 
	{ 
		if (head == null || head.next == null) 
			return head; 
		/* reverse the rest list and put the first element 
        at the end */
		Node rest = reverse(head.next); 
		head.next.next = head; 
		/* tricky step -- see the diagram */
    	head.next = null; 
		/* fix the head pointer */
		return rest; 
	}  /* Function to print linked list */
	static void print() 
	{ 
		Node temp = head; 
		while (temp != null) { 
			System.out.print(temp.data + " "); 
			temp = temp.next; 
		} 
		System.out.println(); 
	} 
	static void push(int data) 
	{ 
		Node temp = new Node(data); 
		temp.next = head; 
		head = temp; 
	} /* Driver program to test above function*/
public static void main(String args[]) 
{ 
	/* Start with the empty list */
	push(20); 
	push(4); 
	push(15); 
	push(85); 
	System.out.println("Given linked list"); 
	print(); 
	head = reverse(head); 
	System.out.println("Reversed Linked list"); 
	print(); 
} } // This code is contributed by Prakhar Agarwal
Posted by: Guest on September-08-2020
-1

reverse linkedlist

Collections.reverse(list);
Posted by: Guest on May-13-2021

Browse Popular Code Answers by Language