recursive java


  • 0
    P

    It seems that everyone comes up with a recursive approach......here is mine:

    /**

    • Definition for singly-linked list.

    • public class ListNode {

    • int val;
      
    • ListNode next;
      
    • ListNode(int x) { val = x; }
      
    • }
      */
      public class Solution {
      public ListNode swapPairs(ListNode head) {
      if(head == null||head.next == null)
      {
      return head;
      }
      return swapnode(head);

      }
      public ListNode swapnode(ListNode begin)
      {
      if(begin == null)
      {
      return null;
      }
      if(begin.next == null)
      {
      return begin;
      }
      ListNode later = begin.next;
      ListNode temp = swapnode(later.next);
      later.next = begin;
      begin.next = temp;
      return later;
      }
      }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.