码迷,mamicode.com
首页 > 其他好文 > 详细

课后习题 3.10 用栈逆置单链表

时间:2020-04-04 11:31:50      阅读:59      评论:0      收藏:0      [点我收藏+]

标签:code   public   ==   Once   too   单链表   first   ace   stack   

LinkList.h

#pragma once
#include<iostream>
using namespace std;

class LNode {
public:
    int data;
    LNode* next;
};

class LinkList {
public:
    LNode* first;

    LinkList() {
        first = new LNode();
        first->data = 666;
        first->next = nullptr;
    }
    void creat(int* arr, int n) {
        LNode* p;
        LNode* s;
        p = first;
        for (int i = 0; i < n; i++) {
            s = new LNode();
            s->data = arr[i];
            s->next = p->next;
            p->next = s;
            p = s;
        }
    }

    void  add(int e) {
        LNode* p;
        LNode* s;
        p = first;
        while (p->next != nullptr) {
            p = p->next;
        }
        s = new LNode();
        s->data = e;
        s->next = p->next;
        p->next = s;
    }

    void show() {
        LNode* p;
        p = first->next;
        while (p != nullptr) {
            cout << p->data << " ";
            p = p->next;
        }
        cout << endl;
    }

};

Stack.h

#pragma once
#include<iostream>
using namespace std;

class Stack {
public:
    int* elements;
    int maxSize;
    int top;

    Stack(int size = 50) {
        maxSize = size;
        elements = new int[maxSize];
        top = -1;
    }
    void push(int e) {
        if (top == maxSize - 1) {
            //
        }
        else {
            elements[++top] = e;
        }
    }
    bool pop(int& e) {
        bool res = true;
        if (top == -1) {
            res = false;
        }
        else {
            e = elements[top--];
        }
        return res;
    }

};

MyTool.h

#pragma once
#include "LinkList.h"
#include"Stack.h"

class MyTool {
public:
    static void turn(LinkList& L) {
        Stack s;
        LinkList L1;
        LNode* p;
        p = L.first->next;
        while (p != nullptr) {
            s.push(p->data);
            p = p->next;
        }
        int temp;
        while (s.pop(temp)) {
            L1.add(temp);
        }
        L = L1;
    }
};

main.cpp

#include"MyTool.h"

int main() {
    LinkList L;
    int arr[] = { 1,2,3,4,5 };
    L.creat(arr, 5);
    MyTool::turn(L);
    L.show();
    return 0;
}

 

课后习题 3.10 用栈逆置单链表

标签:code   public   ==   Once   too   单链表   first   ace   stack   

原文地址:https://www.cnblogs.com/SlowIsFast/p/12630873.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!