24. 两两交换链表中的节点




代码一:

class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        ans = ListNode(0)
        ans.next = head
        cur = ans.next
        while cur.next and cur.next.next:
            temp = cur.next
            cur.next = temp.next
            temp.next = cur.next.next
            cur.next.next = temp
            cur = cur.next.next
	return ans.next

代码二:

class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        ans = ListNode(0)
        ans.next = head
        cur = ans.next
        while cur.next and cur.next.next:
            temp = cur.next
            cur.next = temp.next
            temp.next = temp.next.next
            cur.next.next = temp
            cur = temp
        return ans.next
原文地址:https://www.cnblogs.com/panweiwei/p/12899906.html