leetcode解题方案--024--Swap Nodes in Pairs

来源:互联网 发布:淘宝开店模板 编辑:程序博客网 时间:2024/06/14 14:28

题目

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.

分析

两种方法
一个是循环到底
另外一个是递归,递归的方法很巧妙,反正我是没想到。
看样子递归的功底不够啊

 public static ListNode swapPairs(ListNode head) {        ListNode ans = new ListNode(0);        ans.next = head;        ListNode last = ans;        while (head != null && head.next != null) {            last.next = head.next;            head.next = head.next.next;            last.next.next = head;            head = head.next;            last = last.next.next;        }        return ans.next;    }    public static ListNode swapPairs1(ListNode head) {        if(head == null || head.next == null){            return head;        }        ListNode next = head.next;        head.next = swapPairs(next.next);        next.next = head;        return next;    }
阅读全文
0 0