Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // LeetCode URL: https://leetcode.com/problems/swap-nodes-in-pairs/
- // Definition for singly-linked list.
- class ListNode {
- int val;
- ListNode next;
- ListNode(int x) {
- val = x;
- }
- }
- /**
- * Iterative Solution
- *
- * Time Complexity: O(N)
- *
- * Space Complexity: O(1)
- */
- class Solution1 {
- public ListNode swapPairs(ListNode head) {
- if (head == null || head.next == null) {
- return head;
- }
- ListNode dummy = new ListNode(-1);
- dummy.next = head;
- ListNode cur = head;
- ListNode pre = dummy;
- while (cur != null && cur.next != null) {
- ListNode nextNode = cur.next;
- pre.next = nextNode;
- cur.next = nextNode.next;
- nextNode.next = cur;
- pre = cur;
- cur = cur.next;
- }
- return dummy.next;
- }
- }
- /**
- * Recursive Solution
- *
- * Time Complexity: O(N)
- *
- * Space Complexity: O(N)
- */
- class Solution2 {
- public ListNode swapPairs(ListNode head) {
- if (head == null || head.next == null) {
- return head;
- }
- ListNode nextNode = head.next;
- head.next = swapPairs(nextNode.next);
- nextNode.next = head;
- return nextNode;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement