[LeetCode]페어의 노드 스왑

Inhwan98·2023년 3월 30일
0

PTU STUDY_leetcode

목록 보기
17/24

문제

연결리스트를 입력받아 페어단위로 스왑하라.

예제

  • 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]

코드

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
private:
    int count;
    int temp;

public:
    Solution()
    {
        count = 0;
        temp = 0;
    }
    ListNode* swapPairs(ListNode* head) {
        if (head == NULL) return head;
	    else
	    {
		    if (count % 2 == 0)
		    {
		    	temp = head->val;
		    	if(head->next != NULL) head->val = head->next->val;
		    	count++;
		    	swapPairs(head->next);
		    }
		    else
		    {
		    	head->val = temp;
		    	count++;
		    	swapPairs(head->next);

		    }
	    }
        return head;
    }
};

결과

Runtime 0 ms / Memory 7.6 MB
https://leetcode.com/problems/swap-nodes-in-pairs/submissions/925082657/


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

profile
코딩마스터

0개의 댓글