思路:
就對于這種頭節點發生變化的, 我覺得一般都需要一個虛擬頭節點,然后無非就是讓虛擬頭節點的后兩個節點進行交換,即找到要交換的兩個節點的前一個節點,然后每次循環的時候都要記住這點,這道題就很簡單了
?代碼:
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/
class Solution {public ListNode swapPairs(ListNode head) {ListNode hair = new ListNode(-1,head);ListNode pre = hair, cur = head, temp;while(cur!=null && cur.next!=null){temp = cur.next;cur.next = temp.next;temp.next = cur;pre.next = temp;pre = cur;cur = pre.next;}return hair.next;}
}