How would you reverse a singly-linked list?
Anonymous
public void reverse() { Node temp1 = head.next; Node temp2 = temp1.next; head.next = null; temp1.next = head; // Make head the last node while(temp2.next != null){ Node link = temp2.next; temp2.next = temp1; //Increment the positions temp1 = temp2; temp2 = link; } // Reassign the head if(temp2.next == null){ temp2.next = temp1; head = temp2; } }
Check out your Company Bowl for anonymous work chats.