23. 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.
---
Solution1: Interative
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode swapPairs(ListNode head) { if(head == null || head.next == null) return head; ListNode prev=null, p1 = head, p2 = head.next, next = p2.next; head = p2; // new head while(true){ if(prev != null) prev.next = p2; p2.next = p1; p1.next = next; // update prev = p1; p1 = next; if(p1 == null) return head; // end p2 = p1.next; if(p2 == null) return head; // end next = p2.next; } } }
---
Solution2: Recursive
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode swapPairs(ListNode head) { if(head == null) return null; if (head.next == null) return head; ListNode nextList = swapPairs(head.next.next); ListNode p2 = head.next; head.next = nextList; p2.next = head; return p2; // return the new head } }
浙公网安备 33010602011771号