C++中单链表的基本操作:判空、增、删、显示

写在前面:本文讨论的是带有头结点的单链表

1. 单链表的结点一般用结构体定义,含有两个域,数据域和指针域:struct Node{ int data;  Node * next;}; next是一个指针,指向Node数据类型;

2. 头结点是一个指针,指向Node数据类型,指向第一个结点,

                               

3. 判空,如果头结点指示的是NULL,则该链表为空;否则不为空。

4. 插入一个结点,采用头插法

                              

5. 删除第i个结点q,先定位到第i-1个结点p,使p->next = q->next, 再释放q结点内存

                               

6. 显示,其实是遍历了链表中的每个元素,再输出元素的内容。

下面附上代码。将链表定义为一个类,链表的操作为类的函数。包括两部分:list.h(定义单链表的单个结点和类)、list.cpp(单链表的实现)

list.cpp

#include <iostream>
using namespace std;
#include "list.h"

bool singleList::isEmpty(){
    if (head == NULL)
        return true;
    else
        return false;
}

int singleList::deleteValue(int index){ // /删除链表中第index个结点,并返回该结点的数据
    int j = 0;
    int value;
    if (!isEmpty()){  //如果List不为空,起码有一个元素
        Node *p = head;
        while (j < index - 1 && p != NULL){ //p定位到index的前一个结点
            j++;
            p = p->next;
        }
        Node *q = p->next;
        p->next = q->next;
        value = q->data;
        delete(q);
    }
    return value;
}

void singleList::display(){
    if (!isEmpty()){
        Node * p = head;
        while (p != NULL){
            cout << p->data << ' ';
            p = p->next;
        }
        cout << endl;
    }
    else
        cout << "Empty List!" << endl;
}

void singleList::insertValue(int value){  //将插入元素插入到链表的头部
    if (!isEmpty()){   //处理链表不为空的情况
        Node * n = new Node;
        n->data = value;
        n->next = head;
        head = n;
    }
    else{  //处理链表为空的情况
        Node * n = new Node;
        n->next = NULL;
        n->data = value;
        head = n;
    }
}

list.h

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

class singleList{
    Node * head;
public:
    singleList(){ head = NULL; }  //构造函数,初始化数据成员
    void insertValue(int value);  //向链表中插入一个数据
    int deleteValue(int index);  //删除链表中第index个结点,并返回该结点的数据
    bool isEmpty();   //判断链表是否为空
    void display(); //输出链表中的元素
};







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值