問題:node
Given a linked list, swap every two adjacent nodes and return its head.spa
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.code
解決:it
① 直接交換便可。io
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution { //4ms
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null) return head;
ListNode slow = head;
ListNode fast = head.next;
while(fast != null && fast.next != null && fast.next.next != null){//避免空指針異常
int tmp = slow.val;
slow.val = fast.val;
fast.val = tmp;
slow = fast.next;
fast = slow.next;
}
int tmp = slow.val;//處理最後兩個數
slow.val = fast.val;
fast.val = tmp;
return head;
}
}ast
② class
class Solution {//5ms
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) return head;
ListNode header = new ListNode(-1);
header.next = head;
ListNode cur = header;
ListNode slow = head;
ListNode fast = head.next;
while(slow != null && fast != null){
slow.next = fast.next;
fast.next = slow;
cur.next = fast;
cur = slow;
slow = slow.next;
if(slow != null)fast = slow.next;
}
return header.next;
}
}List