Skip to content
Permalink
master
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
 
 
Cannot retrieve contributors at this time
Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
Note:
Your algorithm should use only constant extra space.
You may not modify the values in the list's nodes, only nodes itself may be changed.
My code:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head==None:
return None
count=0
result=[]
while head.next!=None:
if count%2==0:
tmp_Value=head.val
else:
result.append(head.val)
result.append(tmp_Value)
head=head.next
count+=1
if count%2==0:
tmp_Value=head.val
result.append(tmp_Value)
else:
result.append(head.val)
result.append(tmp_Value)
return result
Solution:
https://leetcode.com/problems/swap-nodes-in-pairs/