[Leetcode] Swap Nodes in Pairs @ Python
Given a linked list, swap every two adjacent nodes and return its head. for example, Given 1-> 2-> 3-> 4, you should return the list as 2-> 1-> 4-> 3. your algorithm shocould use only constant space. you may not modify the values in the list, only nodes itself can be changed. exchange the nodes in the linked list. Given 1-> 2-> 3-> 4, you should return the list as 2-> 1-> 4-> 3. solution: this problem mainly involves the local operations of the linked list. Adding a head node makes it easy to operate. In addition, a [This figure shows my asrman original] Code: copy the Code # Definition for singly-linked list. # class ListNode: # def _ init _ (self, x): # self. val = x # self. next = None class Solution: # @ param a ListNode # @ return a ListNode def swapPairs (self, head): pre = ListNode (0) pre. next = head curr = head = pre while curr and curr. next: # curr = 1, curr. next = 2 pre. next = curr. next #0 --> 2 curr. next = pre. next. next #1 --> 3 # curr. next. next pre. next. next = curr #3 --> 1 pre = curr # pre = 1 curr = curr. next # curr = 3 return head. next