[검지 Offer 노트]: 끝에서 끝까지 체인 테이블 인쇄

2447 단어

제목 설명


ArrayList를 반환하려면 체인 테이블을 입력합니다.

법1: 귀속


include


include


using namespace std;
struct ListNode { public: int val; struct ListNode *next;
/*ListNode(int x) :
val(x), next(NULL)
{
}*/

};
class Solution { private: vector res;
public: vector printListFromTailToHead(ListNode *head) { Recurse(head); return res; }
void Recurse(ListNode *head)
{
    if (head)
    {
        Recurse(head->next);
        res.push_back(head->val);
    }
}

};
int main() { ListNode list[4]; list[0].val = 1; list[0].next = &list[1]; list[1].val = 2; list[1].next = &list[2]; list[2].val = 3; list[2].next = &list[3]; list[3].val = 4; list[3].next = NULL;
Solution solu;
vector res = solu.printListFromTailToHead(list);

cout << "there are " << res.size() << "datas in vector" << endl;
for (int i = 0; i < res.size(); i++)
{
    cout << res[i] << endl;
}
cout << system("pause");
return 0;

}

법2: 창고의'후진 선출'의 사고방식을 이용하여 실현


include


include


include


using namespace std;
struct ListNode { public: int val; struct ListNode *next;
/*ListNode(int x) :
val(x), next(NULL)
{
}*/

};
class Solution { private: vector res;
public: vector printListFromTailToHead(ListNode head) { stack st; ListNode cur = head;
    while (cur)
    {
        st.push(cur->val);
        cur = cur->next;
    }
    while(!st.empty())
    {
        res.push_back(st.top());
        st.pop();
    }
    return res;
}

};
int main() { ListNode list[4]; list[0].val = 1; list[0].next = &list[1]; list[1].val = 2; list[1].next = &list[2]; list[2].val = 3; list[2].next = &list[3]; list[3].val = 4; list[3].next = NULL;
Solution solu;
vector res = solu.printListFromTailToHead(list);

cout << "there are " << res.size() << "datas in vector" << endl;
for (int i = 0; i < res.size(); i++)
{
    cout << res[i] << endl;
}
cout << system("pause");
return 0;

}
우객망 온라인 검사: 스페이스 바 바꾸기_소그물
참고 자료:https://blog.csdn.net/gatieme/article/details/51107632

좋은 웹페이지 즐겨찾기