C++筆記 | 類的應用實例: 單鏈表封裝

C++筆記 類的應用實例:單鏈表封裝

用兩個類表達一個概念

鏈表結點(ListNode)類
鏈表(List)類

//listnode.h
#ifndef LISTNODE_H
#define LISTNODE_H

class List;    // 鏈表類定義(複合方式)
class ListNode // 鏈表結點類
{
public:
    friend class List;              // 鏈表類爲其友元類
    ListNode(int x, ListNode *next) //構造函數
    {
        this->data = x;
        this->next = next;
    }

private:
    int data;       //結點數據, 整型
    ListNode *next; //結點指針
};

class List //鏈表類
{
public:
    List() { first = current = NULL; } //構造函數,使新建的鏈表成爲空鏈表
    int insertData(int x, int i);
    int removeData(int &x, int i);
    void displayAll();

private:
    ListNode *first, *current; //表頭指針,當前指針
};

#endif // LISTNODE_H
//listnode.cpp
#include <iostream>
using namespace std;

#include"listnode.h"

//在鏈表第i個結點處插入新元素x,成功返回1,失敗返回0
int List ::insertData(int x, int i) 
{
    ListNode *p = current;
    current = first;
    for (int k = 0; k < i - 1; k++) //找第 i-1個結點
    {
        if (current == NULL)
            break;
        else
            current = current->next;
    }
    if (current == NULL && first != NULL)
    {
        cout << "無效的插入位置!\n";
        current = p;
        return 0;
    }
    ListNode *newnode = new ListNode(x, NULL);
    if (first == NULL || i == 0) //插在表前
    {
        newnode->next = first;
        first = current = newnode;
    }
    else //插在表中間或表尾
    {
        newnode->next = current->next;
        current = current->next = newnode;
    }
    return 1;
}

//在鏈表中刪除第i個結點,通過x返回其值
int List ::removeData(int &x, int i)
{
    ListNode *p, *q;
    if (i == 0) //刪除表中第 1 個結點
    {
        q = first;
        current = first = first->next;
    }
    else
    {
        p = current;
        current = first;
        //找第 i-1個結點
        for (int k = 0; k < i - 1; k++)
        {
            if (current == NULL)
                break;
            else
                current = current->next;
        }
        if (current == NULL || current->next == NULL)
        {
            cout << "無效的刪除位置!\n";
            current = p;
            return 0;
        }
        else //刪除表中間或表尾元素
        {
            q = current->next; //重新鏈接
            current = current->next = q->next;
        }
    }
    x = q->data; // 返回第 i 個結點的值
    delete q;    // 刪除鏈表節點q
    return 1;
}

//顯示鏈表中所有數據
void List ::displayAll()
{
    ListNode *p = first;
    while (p)
    {
        cout << p->data << ',';
        p = p->next;
    }
    cout << endl;
}
//main.cpp
#include <stdlib.h>
#include <iostream>
#include "listnode.h"
using namespace std;

int main()
{
    List A;//新建空鏈表A
    int x, i;
    for (i = 0; i < 10; i++)
        A.insertData(i, 0); // 每個元素插在鏈表頭部(在鏈表0的地方插入元素i)
    A.displayAll();
    for (i = 0; i < 10; i++)
    {
        if (A.removeData(x, 0)) // 刪除鏈表第一個元素
            cout << x << ',';
    }
    A.displayAll();
    cout << endl;
    
    system("pause");
}
//結果
9,8,7,6,5,4,3,2,1,0,
9,8,7,6,5,4,3,2,1,0,

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