【LintCode 簡單】451. 兩兩交換鏈表中的節點

1.問題描述:

給一個鏈表,兩兩交換其中的節點,然後返回交換後的鏈表。


2.樣例:

給出 1->2->3->4, 你應該返回的鏈表是 2->1->4->3


3.代碼:

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


class Solution:
    """
    @param: head: a ListNode
    @return: a ListNode
    """
    def swapPairs(self, head):
        # write your code here
        if head is None or head.next is None:
            return head
        p=ListNode(0)
        p.next=head
        head=p
        q=head.next
        k=q.next
        while k:
            q.next=k.next
            k.next=q
            p.next=k
            p=q
            if q.next is None:
                q=None
                k=None
            else:
                q=q.next
                k=q.next
        head=head.next
        return head

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章