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.
public ListNode swapPairs(ListNode head) {
// Start typing your Java solution below
// DO NOT write main() function
if(head == null)
return head;
if(head.next == null)
return head;
ListNode odd = head;
ListNode even = head.next;
ListNode pre = head;
odd.next = even.next;
even.next = odd;
head = even;
pre = odd;
while(odd.next != null && odd.next.next != null){
odd = odd.next;
even = odd.next;
odd.next = even.next;
even.next = odd;
pre.next = even;
pre = odd;
}
return head;
}
本文介绍了一种在常数空间复杂度下交换链表中每两个相邻节点的算法。通过迭代方式实现,不修改节点值仅调整节点链接,最终返回交换后的链表头节点。
524

被折叠的 条评论
为什么被折叠?



