24. Swap Nodes in Pairs

    xiaoxiao2021-12-03  47

    Description: 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 should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

    解题思路

    利用两个指针,对next域进行变换即可,这里还做了一些后续操作,可能导致运行时间很慢。(大神可以帮忙提提意见咩?_?)

    Java-Solution

    /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode swapPairs(ListNode head) { if(head == null || head.next == null) return head; ListNode newHead = head.next; while(head != null){ ListNode tmp1 = head; ListNode tmp2 = head.next; try{ head = tmp2.next; tmp1.next = head.next; if(head.next == null){ tmp1.next = head; } tmp2.next = tmp1; } catch(NullPointerException e){ if(tmp2 == null){ break; } tmp2.next = tmp1; tmp1.next = null; break; } } return newHead; } }
    转载请注明原文地址: https://ju.6miu.com/read-679954.html

    最新回复(0)