AI工具人
提示词工程师

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;
    }
}
赞(0) 打赏
未经允许不得转载:XINDOO » Leetcode 24. Swap Nodes in Pairs

评论 抢沙发

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续给力更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫打赏

微信扫一扫打赏

登录

找回密码

注册