public ListNode swapPairs(ListNode node) {
ListNode head = node;
ListNode cur = node;
while (head != null && head.next != null) {
head = reverseList(head, 0);
head.next = cur.next.next;
head = head.next;
cur = head;
}
return node;
}
public ListNode reverseList(ListNode node, int counter) {
if (counter == 1 || node == null || node.next == null) {
return node;
} else {
ListNode newHead = reverseList(node.next, counter++);
node.next.next = node;
node.next = null;
return newHead;
}
}
So this is a leetcode problem.
for example, if the given linked list is 1->2->3->4->5
then the output should be 2->1->4->3->5.
I saw the correct solution but i want to know why this code is not working. Can anyone please help me to understand this?
dsa. Did you read what thedsatag is for before you applied it to your question?return nodebe achieving the result, as it is still the first node in the list? For any list with two or more nodes that is already wrong. In those cases you should certainly not return the originalnode. Please clarify why you are surprised it doesn't work?