21xrx.com
2025-03-21 22:44:42 Friday
文章检索 我的文章 写文章
C++单链表基本操作代码
2023-07-07 17:46:58 深夜i     11     0
C++ 单链表 基本操作 代码

单链表是一种常见的数据结构,它由一系列节点构成,每个节点都包括一个数据项和一个指向下一个节点的指针。单链表具有插入、删除和查找等基本操作,是编写程序时常用的一种工具。下面是C++中单链表基本操作的代码。

定义节点结构体:

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

定义链表类:

class LinkedList{
  Node* head;
public:
  LinkedList() {head=nullptr;}
  void insert(int data); //在链表末尾插入元素
  void remove(int data); //删除指定元素
  void display(); //遍历输出链表中所有元素
};

插入元素:

void LinkedList::insert(int data){
  Node* newNode = new Node;
  newNode -> data = data;
  newNode -> next = nullptr;
  if(head == nullptr)
    head = newNode;
  
  else{
    Node* current = head;
    while(current -> next != nullptr)
      current = current -> next;
    
    current -> next = newNode;
  }
}

删除元素:

void LinkedList::remove(int data){
  if(head == nullptr) return;
  if(head -> data == data){
    Node* temp = head;
    head = head -> next;
    delete temp;
  }
  else{
    Node* current = head;
    while(current -> next != nullptr && current -> next -> data != data)
      current = current -> next;
    
    if(current -> next == nullptr) return;
    Node* temp = current -> next;
    current -> next = current -> next -> next;
    delete temp;
  }
}

遍历输出元素:

void LinkedList::display(){
  Node* current = head;
  while(current != nullptr)
    cout << current -> data << " ";
    current = current -> next;
  
}

使用以上代码,便可实现单链表的基本操作。需要注意的是,在插入和删除元素时要处理好头节点的变动,以及在删除元素时需要判断链表是否为空和存在元素是否为头节点。

  
  

评论区