LeetCode-- Swap Nodes in Pairs

题意:

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

大意:交换相邻两个节点的位置。

public class SwapNodes {
    private class ListNode {
        int val;
        ListNode next;
        ListNode(int x) {
            val = x;
        }
    }                                                      //创建内部类


    public ListNode swapPairs(ListNode head) {
        if (head == null )
            return null;                               //要注意:这里交换两个节点,其实涉及到三个节点------p , q  ,前驱节点 r  (因为要保证r的指针指向正确,可以有多个next指针指向一个节点,但不能没有指向!)
        ListNode r = new ListNode(0);       //创建一个新的节点,暂称为虚节点r;       让这个r作为head,那么这个r就是要找的前驱节点!(链表题目的常用法)
        r.next = head;                            
        head = r;
        ListNode a = head;
        ListNode p = r.next;
        ListNode q = p.next;
        ListNode tmp;                            
        while (p != null && q != null) {
            a.next = q;
            tmp = q.next;
            p.next = tmp;
            q.next = p;                            //交换时要注意的地方
            
            a = p;
            p = tmp;
            if (p != null)                             //这里要注意的是,链表中,p != null时,那么p.next是存在的,可以为null,也可以不为(因为它不是最后一个节点);  

                                                          //但是,p==null, 那么 p.next是不存在的,因为null的指针不知道指向哪里。。。(换句话说,最后一个指针的节点指针next一定为null)
                q = p.next;
        }
        return head.next;
    }
}

链表题目注意:

1、分析,整个过程要涉及到几个节点,前驱怎么办(增加虚节点,将head前移一位),后继怎么办(注意节点next指针,不要报空指针异常);

2、节点多,可以设置tmp,不用多用p.next.next.next这类,太麻烦;

3、节点的next指针问题,每个指针都有它应该指的方向!(牢记)

4、好记性不如烂笔头,在草稿纸上画一画。

态度决定行为,行为决定习惯,习惯决定性格,性格决定命运
原文地址:https://www.cnblogs.com/neversayno/p/5122485.html