[leetcode] 24. Swap Nodes in Pairs

boricat·2021년 10월 28일
0

leetcode

목록 보기
6/14
public class Solution {
    public ListNode swapPairs(ListNode head) {
        if ((head == null)||(head.next == null))
            return head;
        ListNode n = head.next;
        head.next = swapPairs(head.next.next);
        n.next = head;
        return n;
    }
}
public class Solution {
  public ListNode swapPairs(ListNode head) {
    if(head==null || head.next==null) return head;
    ListNode newHead = head.next, a=head,b=a.next,pre = null;
    while(a!=null && b!=null){
      a.next = b.next;
      b.next = a;
      if(pre!=null) pre.next = b;
      if(a.next==null) break;
      b = a.next.next;
      pre = a;
      a = a.next;
    }
    return newHead;
  }
}
public class Solution {
  public ListNode swapPairs(ListNode head) {
    if(head==null || head.next==null) return head;
    ListNode newHead = head.next, a=head,b=a.next,pre = null;
    while(a!=null && b!=null){
      a.next = b.next;
      b.next = a;
      if(pre!=null) pre.next = b;
      if(a.next==null) break;
       a = a.next;
 	   b = a.next;
    }
    return newHead;
  }
}
profile
newbie

0개의 댓글