Monday, January 25, 2016

Reverse Linkedlist Pair Iterative in Java


input        1-->2-->3---->4--->null

Output    2--->1---->4---->3---->null

public ListNode ReversePairIterative(ListNode head) {
ListNode temp1 = null;
ListNode temp2 = null;
while (head != null && head.next != null) {
if (temp1 != null) {
temp1.next.next = head.next;
}
temp1 = head.next;
// System.out.println("temp1--" + temp1.getData());
head.next = head.next.next;
// System.out.println("head.next--" + head.next.getData());
temp1.next = head;
// System.out.println("temp1.next--" + temp1.next.getData());
if (temp2 == null) {
temp2 = temp1;
}
head = head.next;
// System.out.println("head--" + head.getData());
}
return temp2;
}

No comments:

Post a Comment