Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
cur =head
while cur and cur.next:
nxtPair=cur.next.next
second=cur.next
cur.next=nxtPair
second.next=cur
cur=second
cur=cur.next.next
return head
input:[1,2,3,4]
output:
[1,3]
expected:
[2,1,4,3]
I found a solution using dummy linkedlist but without using dummy linkedlist I didn't understand what mistake I made. To have more clarity on this concept can anyone help me with this problem.Here head is not being updated for example , If I have to swap 1,2 to 2,1..head is not being updated to 2,1 instead having only node with 1 as value