24. Swap Nodes in Pairs

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        
        dummy = ListNode()
        dummy.next = head
        curr = head
        last_node = dummy

        while curr != None and curr.next != None:
            curr_next =  curr.next
            last_node.next = curr.next
            curr.next = curr_next.next
            curr_next.next = curr

            last_node = curr
            curr = curr.next
            
        
        dummy = dummy.next
        return dummy

This is my first time solution when I approach to this question. As normal, create a dummy node linked to the head, which helps with the declaring the last_node variable. And also declare the variable curr that equal to head.

Then for the condition of the while loop, we need to ensure the curr node is not None, to prevent for example, if head = None, curr.next will raise an AttributeError, also, when let say there are totally two nodes in a linkedlist, after swapping, curr would equal to curr.next which is also None, and it could raise an AttributeError. Verify curr.next not equal to None because there is no more node to swap if this condition met.

for the code in while loop, it is basically doing the things as follow:

the number beside the line is line of the instrucution within the while loop.

finally, after the while loop, remove the dummy node and return dummy.

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值