【LeetCode】Swap Nodes in Pairs 連結串列指標的應用

HIT_微笑前進發表於2015-03-20

題目: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>


相關文章