每天AC系列(十):两两交换链表中的节点

时间:2020-02-01 00:38:28   收藏:0   阅读:73
1 题目

LeetCode第24题,交换链表的相邻节点.
技术图片

2 直接交换

直接交换的思想很简单,遍历一次链表,进行两两交换.

ListNode newHead = new ListNode(0);
newHead.next = head;
ListNode before = newHead;
ListNode first = head;
ListNode second = head.next;
ListNode move;

while(true)
{
    move = second.next;
    first.next = second.next;
    second.next = first;

    before.next = second;
    before = first;

    first = move;

    if(move != null && move.next != null)
    {
        second = move.next;
        move = move.next.next;
    }
    else 
        break;
}
return newHead.next;

虽然思想简单,但是,并不好实现,有点绕,首先增加一个头节点,first,second当前要交换的两个节点,before为first的前一个节点,用来连上first,move是为了更新first与second节点的节点,进入while循环后,首先把first与second交换,接着用before连上first同时更新before,然后利用move更新first与second.
技术图片

3 递归交换

递归交换就是每次只交换头两个节点,然后把第三个节点作为下一次递归交换的头结点继续递归交换.

if(head != null && head.next != null)
{
    ListNode t = head.next;
    head.next = swapPairs(t.next);
    t.next = head;
    return t;
}
return head;

要注意交换的顺序,先赋值head.next,head.next为剩下的节点,然后把t连上head.
技术图片

4 插入法

新建一个链表,采用尾插法,依次插入交换的节点.
对于原链表设置两个指针a与b,令a指向首个节点,b指向第二个节点,然后对于新链表,先插入b,再插入a,最后更新a,b,使a,b都指向后继的后继,这样依次插入b与a就会得到所需的链表.

if(head == null || head.next == null)
    return head;
ListNode a = head;
ListNode b = head.next;
ListNode newHead = new ListNode(0);
ListNode t = newHead;
while(a != null && b != null)
{
    t.next = new ListNode(b.val);
    t = t.next;
    t.next = new ListNode(a.val);
    t = t.next;
    if(b.next != null)
        b = b.next.next;
    a = a.next.next;
}
if(a != null)
    t.next = new ListNode(a.val);
return newHead.next;

在更新a,b时,对于a不需要判断a.next是否为空,因为a.next肯定为b,肯定不为空,但是对于b,当到达最后一个节点时,b.next为空,因此需要加上判断.当a,b其中一个为空后跳出循环,最后的判断a是否为空表示节点个数为奇数,此时a指向最后一个节点,直接插入a.
技术图片

5 插入法改进

对于上面的插入法,由于ab是连在一起的,因此可以只使用其中一个,再优化判空与插入操作.

ListNode newHead = new ListNode(0);
ListNode t = newHead;
while(head != null)
{
    if(head.next != null)
    {
        t.next = new ListNode(head.next.val);
        t = t.next;
    }
    t.next = new ListNode(head.val);
    t = t.next;
    if(head.next == null)
        break;
    head = head.next.next;
}
return newHead.next;

要注意while中的判空条件,因为节点的个数有可能是奇数,在插入后一个节点前需要先判断是否为空,再插入前一个节点.
技术图片

6 源码

github

码云

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!