File tree Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Expand file tree Collapse file tree 1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change 1+ //Iterative version
2+ class Solution {
3+ public ListNode swapPairs (ListNode head ) {
4+ if (head == null || head .next == null ) return head ;
5+ ListNode dummy = new ListNode (0 );
6+ dummy .next = head ;
7+ ListNode temp = dummy ;
8+ while (temp .next !=null && temp .next .next !=null ) {
9+ ListNode first = temp .next ;
10+ ListNode second = temp .next .next ;
11+ temp .next = second ;
12+ first .next = second .next ;
13+ second .next = first ;
14+ temp = first ;
15+ }
16+ return dummy .next ;
17+
18+ }
19+ }
20+
21+ //Recursive version
22+ class Solution {
23+ public ListNode swapPairs (ListNode head ) {
24+ if (head == null || head .next == null )
25+ return head ;
26+ ListNode p = head .next ;
27+ head .next = swapPairs (head .next .next );
28+ p .next = head ;
29+ return p ;
30+ }
31+ }
You can’t perform that action at this time.
0 commit comments