课后习题 2-17 单链表逆转

题目:通过一遍遍历逆转单链表,使头结点指向最后一个结点。

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 show() {
        LNode* p;
        p = first->next;
        while (p != nullptr) {
            cout << p->data << " ";
            p = p->next;
        }
        cout << endl;
    }

    void turn() {
        LNode* p1, * p2, * p3;
        p1 = first->next;
        p2 = p1->next;
        p3 = p2->next;
        p1->next = nullptr;
        while (p3 != nullptr) {
            p2->next = p1;
            p1 = p2;
            p2 = p3;
            p3 = p3->next;

        }
        p2->next = p1;
        first->next = p2;
    }

};

main.cpp

#include"LinkList.h"

int main() {
    LinkList L;
    int a[] = { 1,2,3,4,5,6,7,8,9 };
    L.creat(a, 9);
    L.show();
    L.turn();
    L.show();
    return 0;
}

 

posted @ 2020-03-23 10:40  落地就是一把98K  阅读(179)  评论(0)    收藏  举报