21xrx.com
2024-09-20 00:27:32 Friday
登录
文章检索 我的文章 写文章
C++单向链表的实现
2023-07-14 10:44:15 深夜i     --     --
C++ 单向链表 实现

C++单向链表是一种数据结构,用于存储一系列具有相同类型的元素。链表的每个节点都包含一个数据项和一个指向下一个节点的指针,它们按照某种顺序排列在一起。

C++单向链表的实现可以分为3步:

1. 定义链表节点

链表的节点包含两个部分:数据项和下一个节点的指针。下面是一个节点的定义:


struct Node {

  int data;

  Node* next;

};

2. 实现链表类

C++单向链表可以通过一个链表类来实现。链表类负责链表的插入和删除操作,以及链表节点的遍历。下面是一个链表类的定义,其中使用了一个头节点来指示链表的开头:


class LinkedList {

public:

  LinkedList();

  ~LinkedList();

  void insert(int value);

  void remove(int value);

  void display();

private:

  Node* head;

};

3. 实现链表类中的操作

链表类中包含了3个方法:插入、删除和遍历。这些方法的实现很简单,我们只需要使用链表节点的指针来操作即可。

插入方法:


void LinkedList::insert(int value) {

  Node* newNode = new Node;

  newNode->data = value;

  if (head == nullptr)

    head = newNode;

   else {

    Node* current = head;

    while (current->next != nullptr)

      current = current->next;

    

    current->next = newNode;

  }

}

删除方法:


void LinkedList::remove(int value) {

  if (head == nullptr)

    return;

  

  if (head->data == value) {

    Node* temp = head->next;

    delete head;

    head = temp;

  } else {

    Node* previous = head;

    Node* current = head->next;

    while (current != nullptr && current->data != value)

      previous = current;

      current = current->next;

    

    

    if (current != nullptr)

      previous->next = current->next;

      delete current;

    

  }

}

遍历方法:


void LinkedList::display() {

  Node* current = head;

  while (current != nullptr)

    std::cout << current->data << "-->";

    current = current->next;

  

  std::cout << "nullptr\n";

}

通过以上3步,我们就可以实现一个完整的C++单向链表了。在我们的链表类中,我们可以存储任何类型的数据,并且可以灵活地插入和删除,以及遍历整个链表。在实际开发中,单向链表是非常常用的一种数据结构,尤其是当我们需要在大量数据中进行插入和删除操作时。

  
  
下一篇: C++读取.mat文件

评论区

{{item['qq_nickname']}}
()
回复
回复