1. 程式人生 > >【leetcode】24. Swap Nodes in Pairs(JAVA)

【leetcode】24. Swap Nodes in Pairs(JAVA)

題目連結

提交程式碼:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
    	 if(head==null||head.next==null)	return head;

    	   int tmp;
    	   ListNode p=
head; while(p!=null&&p.next!=null) { tmp=p.val; p.val=p.next.val; p.next.val=tmp; p=p.next.next; } return head; } }

執行結果: 在這裡插入圖片描述