文章--LeetCode算法--SwapNodesinPairs

SwapNodesinPairs

问题描述

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 class Solution {
        public ListNode swapPairs(ListNode head) {
            ListNode p = head;
            if (p == null || p.next == null)
                return head;
            ListNode newHead = p.next;
            p.next = p.next.next;
            newHead.next = p;
            p = newHead.next.next;
            newHead.next.next = swapPairs(p);
            return newHead;
        }
    }
posted @ 2019-07-24 10:20  AI,me  阅读(99)  评论(0)    收藏  举报