Permalink
Cannot retrieve contributors at this time
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?
LeetCode/swap-nodes-in-pairs
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
45 lines (39 sloc)
1.12 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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/ |