Home [Medium] Swap Nodes in Pairs
Post
Cancel

[Medium] Swap Nodes in Pairs

‘Swap Nodes in Pairs (Medium)


📌 Problem

https://leetcode.com/problems/swap-nodes-in-pairs/

📌 Answer

  • Iterative ```java /**
  • Definition for singly-linked list.
  • public class ListNode {
  • int val;
  • ListNode next;
  • ListNode() {}
  • ListNode(int val) { this.val = val; }
  • ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  • } */ class Solution { public ListNode swapPairs(ListNode head) {

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
     ListNode temp = head;
        
     while (head != null && head.next != null) {
         int curr = head.val;
         int next = head.next.val;
         head.next.val = curr;
         head.val = next;
         head = head.next.next;
     }
    
     return temp;  } } ```
    
  • Recursive
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    class Solution {
      public ListNode swapPairs(ListNode head) {
          if (head == null || head.next == null) return head;
            
          ListNode nxt = head.next;
          head.next = swapPairs(nxt.next);
          nxt.next = head;
            
          return nxt;
      }
    }
    
  • Reference
This post is licensed under CC BY 4.0 by the author.

[Medium] Remove Duplicates from Sorted List II

[Medium] Rotate List

Comments powered by Disqus.