两两交换链表中的节点

it2026-08-23  3

1->2->3->4->5 ==》 2->1->4->3->5

非递归求解

public ListNode swapPairs(ListNode head) { if (head==null||head.next==null) return head; ListNode pre=new ListNode(0); pre.next=head; ListNode temp=pre; while (temp.next!=null&&temp.next.next!=null){ ListNode start=temp.next; ListNode end=temp.next.next; temp.next=end; start.next=end.next; end.next=start; temp=start; } return pre.next; }

递归求解

/** * 递归求解 * @return */ public ListNode swapPairs2(ListNode head){ if (head==null||head.next==null) return head; ListNode nextNode=head.next; head.next=swapPairs(nextNode.next); nextNode.next=head; return nextNode; }
最新回复(0)