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即可

posted @ 2022-11-04 09:48  MarkLeeBYR  阅读(13)  评论(0)    收藏  举报