24. Swap Nodes in Pairs
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.
Solution 1:
public ListNode swapPairs(ListNode head) {
ListNode dmy = new ListNode(0);
ListNode cur = dmy;
dmy.next = head;
while (cur.next != null && cur.next.next != null) {
ListNode first = cur.next;
ListNode sec = first.next;
ListNode third = sec.next;
cur.next = sec;
sec.next = first;
first.next = third;
cur = first;
}
return dmy.next;
}
Solution 2:
参考题目25,k为2即可
浙公网安备 33010602011771号