Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example:
Given1->2->3->4 you should return the list as 2->1->4->3
迭代法:时间复杂度O(n),空间复杂度O(1)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode prev = dummy;
ListNode cur = head;
while(cur!=null && cur.next!=null){
ListNode next = cur.next;
cur.next = next.next;
next.next = prev.next;
prev.next = next;
prev = cur;
cur = cur.next;
}
return dummy.next;
}
}
递归法:时间复杂度O(n),空间复杂度O(n)
/**
* 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 second = head.next;
ListNode third = second.next;
second.next = head;
head.next = swapPairs(third);
return second;
}
}