Leetcode 24.Swap Nodes in Pairs

来源:互联网 发布:什么是js模块化 编辑:程序博客网 时间:2024/05/21 10:06

题目链接 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;    }}
原创粉丝点击