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

借助新增加的结点

class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head:
            return 
        if head.next==None:
            return head
        a=ListNode(0)
        p=head
        q=p.next
        head=a
        while p and q:
            a.next=q
            p.next=q.next
            q.next=p
            a=p
            p=p.next
            if p!=None:
                q=p.next
        return head.next
执行用时 :16 ms, 在所有 python 提交中击败了94.05%的用户
内存消耗 :11.7 MB, 在所有 python 提交中击败了39.45%的用户
 
人家将p和q的定义放在循环内部,就不需要考虑是不是不存在的情况。。。。
class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        thead = ListNode(-1)
        thead.next = head
        c = thead
        while c.next and c.next.next:
            a, b=c.next, c.next.next
            c.next, a.next = b, b.next
            b.next = a
            c = c.next.next
        return thead.next

作者:wu-yan-34
链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs/solution/bi-jiao-zhi-jie-gao-xiao-de-zuo-fa-han-tu-jie-by-w/

 

还有递归的解法,留在下次尝试。
 
——2019.10.25
 
 

public ListNode swapPairs(ListNode head) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        if(head == null || head.next == null){
            return head;
        }//排除链表长度小于2的情况
        ListNode t = dummy.next.next;
        ListNode p = dummy.next;
        ListNode s = dummy;
        while( t != null){
            s.next = t;
            p.next = t.next;
            t.next = p;

            s = p;
            if(p.next!=null) {
                t = p.next.next;
                p = p.next;
            }else{
                return dummy.next;
            }
        }
        return dummy.next;
    }

 

 

顺利

——2020.7.14

posted @ 2019-10-25 10:04  欣姐姐  阅读(155)  评论(0编辑  收藏  举报