劍指offer——從尾到頭打印鏈表

題目:輸入一個鏈表的頭結點,從尾到頭反過來打印出每個節點的值。

說實話,我最開始的思路是,定義一個輔助數組,將這個鏈表的值依次存入到數組中去,壓根就沒打算用棧這個數據結構的。我感覺兩個效率差不多吧。有想法的通知麻煩指出來。

算法實現

#include <iostream>
#include<stack>
using namespace std;

struct Node
{
    int val;
    Node * next;
};

struct List
{
    Node * head;
    int size;
};

void initList(List * list)
{
    list->head = new Node();
    list->size = 0;
}

void addList(List * list, int array[], int len)
{
    int i;
    Node * p = list->head;
    for (i = 0; i < len; i++)
    {
        Node * temp = new Node();
        temp->next = NULL;
        temp->val = array[i];
        p->next = temp;
        p = temp;
        list->size++;
    }
}
//倒序輸出
void DaoXuShuChu(List list)
{
    Node * pHead = list.head;
    if (pHead->next == NULL && list.size == 0)
    {
        cout << "鏈表爲空" << endl;
        return;
    }

    int length = list.size;
    int i = length;
    int * pValue = new int[length];

    Node * p = pHead->next;     //讓p指向鏈表第一個元素

    while (p != NULL)
    {
        pValue[--i] = p->val;
        p = p->next;
    }

    for (int j = 0; j < length; j++)
        cout << pValue[j] << endl;

}

//倒序輸出1
void DaoXuShuChu1(List list)
{
    Node * pHead = list.head;
    if (pHead->next == NULL && list.size==0)
    {
        cout << "鏈表爲空" << endl;
        return;
    }

    stack<int> ss;

    Node * p = pHead->next;     //讓p指向鏈表第一個元素

    while (p!=NULL)
    {
        ss.push(p->val);
        p = p->next;
    }

    //返回在堆棧中元素數目
    int n = ss.size();
    for (int i = 0; i < n; i++)
    {
        cout << ss.top() << endl;
        ss.pop();
    }
}

//倒序輸出2
void DaoXuShuChu2(List list)
{
    Node * pHead = list.head;
    if (pHead->next == NULL && list.size == 0)
    {
        cout << "鏈表爲空" << endl;
        return;
    }
    //知識改變了棧結構中存儲的數據類型而已,根本就算不上另外一種。
    stack<Node*> ss;

    Node * p = pHead->next;     //讓p指向鏈表第一個元素

    while (p != NULL)
    {
        ss.push(p);
        p = p->next;
    }

    //返回在堆棧中元素數目
    int n = ss.size();
    for (int i = 0; i < n; i++)
    {
        cout << (ss.top())->val << endl;
        ss.pop();
    }
}
//倒序輸出3
//採用遞歸也可以實現。我就沒寫了,有興趣的人可以試試

int main()
{
    List list;
    initList(&list);

    int array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    addList(&list, array, 10);

    DaoXuShuChu(list);

    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章