c/c++シングルチェーンフォームチェーンテーブル作成末尾から印刷

1851 ワード

剣指offerという本では、単鎖表の末尾から印刷する方法は2つあると指摘されていますが、この2つの方法はチェーン表を修正しない上で行われています.
1:スタックデータ構造を使用して、単一チェーンテーブルを遍歴し、データをスタックに保存し、スタックの「先進後出」特性を利用して、単一チェーンテーブルの末尾から印刷を実現する.しかし、この方法は追加のストレージスペースのオーバーヘッドをもたらします.
2:再帰的な方法を使用し、ここで本質もスタックの特性を利用する.再帰的な本質はスタック構造であるからである.しかし、この方法では、チェーンテーブルのデータ量が大きい場合に、プログラムスタックがオーバーフローする可能性があります.
以下の手順では、上記の2つの方法のチェーンテーブル印刷をそれぞれ示します.
#include 
#include 
using namespace std;

struct Node
{
    int m_iValue;
    Node* m_pNext;
};

void printLinkReverse(Node* head)
{
    if(head!=nullptr)
    {
        if(head->m_pNext!=nullptr)
            printLinkReverse(head->m_pNext);
        cout << head->m_iValue << " ";
    }
}

void printLinkReverse2(Node* head)
{
    stack Nodestack;
    Node* pTmp=head;
    while(pTmp!=nullptr)
    {
        Nodestack.push(pTmp->m_iValue);
        pTmp=pTmp->m_pNext;
    }
    while(!Nodestack.empty())
    {
        cout << Nodestack.top() << " ";
        Nodestack.pop();
    }
}

void print(Node* head)
{
    while(head->m_pNext!=nullptr)
    {
        cout << head->m_iValue << " ";
        head=head->m_pNext;
    }
    cout << head->m_iValue << endl;
}

Node* instNodeHead(Node* head, int value)
{
    Node* p0=new Node;
    p0->m_iValue=value;
    p0->m_pNext=head->m_pNext;
    head->m_pNext=p0;
    return head;
}

Node* create()
{
    Node* head = new Node;
    head->m_iValue=0;
    head->m_pNext=nullptr;
    int value;
    while(cin>>value)
    {
        if(value==0)break;
        instNodeHead(head,value);
    }
    return head;
}

int main(void)
{
    Node* pHead;
    pHead=create();
    print(pHead);
    printLinkReverse(pHead);
    printLinkReverse2(pHead);

    return 0;
}