algorithms

Algorithm implementations
git clone git://git.laack.co/algorithms.git
Log | Files | Refs | README

swap.py (726B)


      1 # Definition for singly-linked list.
      2 # class ListNode:
      3 #     def __init__(self, val=0, next=None):
      4 #         self.val = val
      5 #         self.next = next
      6 class Solution:
      7     def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]:
      8 
      9         ls = []
     10         node1 = head
     11 
     12         while node1 != None:
     13             ls.append(node1)
     14             print(node1.val)
     15             node1 = node1.next
     16         
     17         for i in range(0,len(ls) - 1, 2):
     18             tmp = ls[i]
     19             ls[i] = ls[i+1]
     20             ls[i+1] = tmp
     21 
     22         for i in range(0,len(ls) - 1):
     23             ls[i].next = ls[i+1]
     24         
     25         if len(ls) > 0:
     26             ls[len(ls) - 1].next = None
     27             head = ls[0]
     28         
     29         return head