美文网首页
LeetCode 24. Swap Nodes in Pairs

LeetCode 24. Swap Nodes in Pairs

作者: chengruru | 来源:发表于2018-08-09 15:22 被阅读0次
题目

       将链表中相邻的两个节点交换位置,注意第一个节点与第二个节点要交换位置,第三个节点与第四个节点要交换位置, 而第二个节点不用与第三个节点交换位置。

Note:

       1.不允许修改节点的值;
       2.只能用常量的额外空间.

思路分析
23.png

代码实现如下:

public ListNode swapPairs(ListNode head) {
        //如果链表为空或者只有一个节点,那么就直接返回head节点即可
        if(head == null ||head.next == null)
            return head;
        ListNode preNode, currentNode, afterNode;
        currentNode = head;
        //添加辅助头节点,这是链表中比较常用的小技巧,因为这样可以避免处理head的边界情况
        head = new ListNode(0);
        head.next = currentNode;
        preNode = head;
        while (currentNode!=null && currentNode.next!=null){
            afterNode = currentNode.next;
            currentNode.next = afterNode.next;
            afterNode.next = currentNode;
            preNode.next = afterNode;
            preNode = currentNode;
            currentNode = currentNode.next;

        }
        return head.next;
    }

相关文章

网友评论

      本文标题:LeetCode 24. Swap Nodes in Pairs

      本文链接:https://www.haomeiwen.com/subject/aqxcbftx.html