Given a linked list, swap every two adjacent nodes and return its head.
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.
這道題自己想的方法沒有寫出來,然后看了別人的解法。發現意思跟我的思路差不多,但細節很多地方我確實想不出來。linkedlist的題目很多細節問題,哪個該連哪個,對我來說現在很容易錯或者陷入混亂。
該解法實際上仍然是維護三個pointers:prev, curt, temp.
以節點為偶數個時舉例:
WechatIMG50.jpeg
WechatIMG51.jpeg
當節點數為偶數的時候,是curt == null退出循環;當節點數為奇數的時候,是curt.next == null退出循環。
WechatIMG52.jpeg
/**
* 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;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode prev = dummy;
ListNode curt = head;
while (curt != null && curt.next != null){
ListNode temp = curt.next.next;
curt.next.next = curt;
prev.next = curt.next;
curt.next = temp;
prev = curt;
curt = curt.next;
}
return dummy.next;
}
}