Leetcode 24. Swap Nodes in Pairs

题目链接 Leetcode 24. Swap Nodes in Pairs

  给你一个链表,交换相邻两个节点,例如给你 1->2->3->4,输出2->1->4->3。

  我代码里在head之前新增了一个节点newhead,其实是为了少写一些判断head的代码。

public class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode p = head;
        ListNode pre = new ListNode(0);
        pre.next = head;
        ListNode newhead = pre;
        while (null != p && null != p.next) {  //两两节点做交换 
        //其实交换两个节点涉及三个节点的变更
            ListNode q = p.next;
            pre.next = p.next;
            p.next = q.next;
            q.next = p;
            pre = p;
            p = p.next;
        }
        return newhead.next;
    }
}
打赏

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.