Saturday, August 27, 2011

Reverse a pair of elements in a linked list.

reverse a pair of elements in a linked list. abcd - badc

// returns head of new list
public Node reverseInPairs(Node head) {

Node first = head;
	Node second = first.next;



if (first == null || second == null) {
		return head; 
// can't reverse a singleton/empty list. head remains the same
	}

while (first != null && second != null) {
		temp = first.next.next;
		second.next = first;
                first.next = temp;
		first = temp;
		second = first.next;
	}

return head.next;
}

1 comment: