【LeetCode】Swap Nodes in Pairs 链表指针的应用

题目:swap nodes in pairs

<span style="font-size:18px;">/**
 * LeetCode Swap Nodes in Pairs 
 * 题目:输入一个链表,要求将链表每相邻的两个节点交换位置后输出
 * 思路:遍历一遍就可以,时间复杂度O(n)
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
package javaTrain; 

public class Train12 {
	public ListNode swapPairs(ListNode head) {
		if(head == null || head.next == null) return null;
        ListNode pNode;
        pNode = head;
        while(pNode != null && pNode.next != null){
        	int temp; 
        	temp = pNode.val;
        	pNode.val = pNode.next.val;
        	pNode.next.val = temp;
        	pNode = pNode.next.next; 
        }
        return head;
    }
}
</span>


原文地址:https://www.cnblogs.com/yfceshi/p/6880279.html