交换链表中相邻节点的位置

来源:互联网 发布:nginx m3u8 点播 编辑:程序博客网 时间:2024/05/29 08:19

这里写图片描述

public class Solution {    public ListNode swapPairs(ListNode head) {        if(head == null) return head;        ListNode pre = null;        ListNode cur = head;        ListNode res = head;        boolean flag = true;        while (cur != null) {            ListNode tmp = cur;            ListNode cnext = cur.next;            if(pre != null) pre.next = cnext;            if(cnext == null) {                if(pre != null) pre.next = cur;                return res;            }            ListNode tnext = cnext.next;            pre = tmp;            cnext.next = cur;            cur = tnext;            pre.next = null;            if(flag) {                res = cnext;                flag = false;            }        }        return res;    }}