LeetCode - 24. Swap Nodes in Pairs(LinkedList, Recursion)***

YAMAMAMO·2022년 10월 25일
0

LeetCode

목록 보기
73/100

문제

Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)

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

Example 1:

Input: head = [1,2,3,4]
Output: [2,1,4,3]

Example 2:

Input: head = []
Output: []

Example 3:

Input: head = [1]
Output: [1]

풀이


class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head==null) return head;
        if(head.next==null) return head;
        
        ListNode cur = new ListNode(0);
        cur.next = head;
        ListNode newHead = cur;
    
        while(cur.next!=null&&cur.next.next!=null){
            
            ListNode n1=cur.next;
            ListNode n2=n1.next;
            ListNode next=n2.next;
            
            cur.next=n2;
            n2.next=n1;
            n1.next=next;
            
            cur=n1;
        }
        
        return newHead.next;
    }
} 
profile
안드로이드 개발자

0개의 댓글