[LeetCode]역순 연결 리스트

Inhwan98·2023년 2월 7일
0

PTU STUDY_leetcode

목록 보기
15/24

문제

연결 리스트를 뒤집어라

예제

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

코드

/**
 * 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:
	ListNode* rhead;
	ListNode* rtail;
    stack<int> st;
public:
    void addNode(int n)
    {
        ListNode* temp = new ListNode;
        temp->val = n;
        temp->next = NULL;
        if(rhead == NULL)
        {
            rhead = temp;
            rtail = temp;
        }
        else
        {
            rtail->next = temp;
            rtail = temp;
        }
    }
    void pushStack(ListNode* head)
    {
    	if (head == NULL)
    	{
    		cout << "\n";
	    }
	    else
	    {
		    st.push(head->val);

		    if(head->next != NULL) pushStack(head->next);
    	}
    }
   ListNode* reverseList(ListNode* head)
    {
	    pushStack(head);
	    while (!st.empty())
	    {
		    addNode(st.top());
		    st.pop();
	    }
    	return rhead;
    }  



};

풀이

1.

  • rhead의 연결리스트를 생성할 것이다.

2.

  • 먼저 pushStack함수에서 head에서 받아온 입력값들을 stack에 차곡차곡 쌓아준다.

3.

  • 스택이 공백이 될때까지 스택의 맨 위부터 rhead에 노드로 추가해준뒤, rhead를 return한다.

결과

Runtime 8 ms / Memory 88 MB
https://leetcode.com/problems/reverse-linked-list/submissions/893526853/


https://leetcode.com/problems/reverse-linked-list/

profile
코딩마스터

0개의 댓글