My simple Accepted Java Code, nonrecursive soluntion


  • 0
    S

    This i s a simple solution using LinkedList and constand space to deal with the problem,

    public  ListNode swapPairs(ListNode head) {
                if (head == null || head.next == null) {
                    return head;
                }
                LinkedList<ListNode> LL = new LinkedList<ListNode>();
                while (head != null) {
                    LL.add(head);
                    head = head.next;
                }
                for (int i = 1; i < LL.size(); i = i + 2) {
                    LL.get(i).next = null;
                    LL.get(i - 1).next = null;
                    LL.add(i - 1, LL.remove(i));
                }
                LL.get(LL.size() - 1).next = null;
        
                for (int i = 0; i < LL.size() - 1; i++) {
                    LL.get(i).next = LL.get(i + 1);
                }
                return LL.get(0);
            }

  • 0
    Y

    hi Shen,
    Your algorithm should use only constant space !! your solution is wrong


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.