c++实现链表的倒序操作

c++实现链表的倒序操作

首先是Node.h

#pragma once
#include<iostream>
using namespace std;
class LinkNode
{
public:
    int data;
    LinkNode * next;
    LinkNode() {};
    LinkNode(const int &el, LinkNode * ptr = 0)
    {
        data = el;
        next = ptr;
    }
};

class LinkList
{
public:
    LinkList();
    ~LinkList();
    void CreatLinkList(int length);
    void Print();
    void LinkListEx();
private:
    LinkNode * head, *tail;  //表头和表尾指针
    int length;//当前链表长度 
};

LinkList::LinkList()
{
    length = 0;
    head = NULL;
    tail = NULL;
}

LinkList::~LinkList()
{
    LinkNode* temp;
    int i=0;
    while (i < length)
    {
        temp = head;
        head = head->next;
        delete temp;
        i++;
    }
}

void LinkList::CreatLinkList(int l)
{
    length = l;
    if (length == 0)
    {
        cout << "Failed to create" << endl;
    }
    else
    {
        head = new LinkNode;
        tail = head;
        cout << "input the data of this node: ";
        cin >> head->data;
        tail->next = NULL;
        LinkNode * temp;
        for (int i = 1; i < length; i++)
        {
            temp = new LinkNode;
            tail->next = temp;
            temp->next = NULL;
            tail = temp;
            cout << "input the data of this node: ";
            cin >> temp->data;

        }
    }
}

void LinkList::Print()
{
    if (length == 0)
    {
        cout << "Empty list" << endl;
    }
    else
    {
        LinkNode * temp = head; 
        while (temp != NULL)
        {
            cout << temp->data<< endl;
            temp = temp->next;
        }
    }

}

void LinkList::LinkListEx()
{
    if (head == NULL)
        return;
    LinkNode *curNode = head,//当前结点
        *nextNode = head->next, //下一个节点
        *temp;//中间结点
    while (nextNode != NULL)
    {
        temp = nextNode->next;//temp指向第三个节点
        nextNode->next = curNode;//改变改变第二个指针域指向
        curNode = nextNode;//curNode指向第二个节点
        nextNode = temp;//nextNode指向第三个节点
    }
    head->next = NULL;//头指针一直没改变,经过上面的变换之后须将头节点指针域变为NULL,作为尾结点
    head = curNode;//将头指针指向改变
}

xtNode指向第三个节点
}
head->next = NULL;//头指针一直没改变,经过上面的变换之后须将头节点指针域变为NULL,作为尾结点
head = curNode;//将变}

main函数位于LinkList.cp #pragma once
#include
#include”Node.h”
using namespace std;

int main()
{
    LinkList L;
    L.CreatLinkList(3);
    L.Print();
    L.LinkListEx();
    L.Print();

L.Print();} 

猜你喜欢

转载自blog.csdn.net/HurryRabbit/article/details/78011354
今日推荐