Leetcode 24 Swap Nodes in Pairs

来源:互联网 发布:SSL协议所使用的端口是 编辑:程序博客网 时间:2024/06/03 19:11

Swap Nodes in Pairs

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.

Solution1

  • 每一次处理两个节点,主要注意的是处理过程中暂存好后面的节点。
public class Solution {    public ListNode swapPairs(ListNode head) {        ListNode dummy = new ListNode(-1);        dummy.next = head;        ListNode prev = dummy;        while(prev.next!=null&&prev.next.next!=null){            ListNode temp1 = prev.next;//暂存好第一个节点            prev.next = prev.next.next;            ListNode temp2 = prev.next.next;//暂存好第二个节点            prev.next.next = temp1;            temp1.next = temp2;            prev = temp1;        }        return dummy.next;            }}

Solution2

  • 递归解法,显得更加清晰易懂。但一般不太提倡递归,因为会有隐形的栈空间调用。
public class Solution {    public ListNode swapPairs(ListNode head) {        if(head==null||head.next==null) return head;        ListNode first = head;        ListNode second = head.next;        first.next = swapPairs(second.next);        second.next = first;        return second;          }}
0 0
原创粉丝点击