21xrx.com
2025-03-17 14:25:33 Monday
文章检索 我的文章 写文章
C++单链表创建代码
2023-07-04 23:53:01 深夜i     --     --
C++ 单链表 创建 代码

单链表是一种常见的数据结构,它由一个个节点组成,每个节点包含一个存储数据的元素和一个指向下一个节点的指针。

以下是使用C++语言实现单链表的代码。

首先,我们需要定义节点类型:

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

其中,data存储节点中的数据,next是指向下一个节点的指针。

接下来,我们需要创建单链表的头节点。在这个节点之后,我们会添加其他节点。因此,这个节点的data可以为空,next为null。

Node* head = new Node();
head->data = NULL;
head->next = NULL;

我们还需要定义一个函数来向单链表中添加节点。这个函数需要传入一个int类型的数据,以便将数据存储在节点中。

void addNode(int data) {
  Node* newNode = new Node();
  newNode->data = data;
  newNode->next = NULL;
  if (head->next == NULL) // 如果链表中没有节点
    head->next = newNode;
  
  else { // 如果链表中已有节点
    Node* temp = head;
    while (temp->next != NULL)
      temp = temp->next;
    
    temp->next = newNode;
  }
}

在这个函数中,我们首先创建了一个新的节点,并将传入的数据存储在节点中。接着,我们判断链表中是否已存在节点。如果链表中没有节点,我们将新节点连接到头节点之后。如果链表中已存在节点,我们需要遍历整个链表,找到最后一个节点,然后将新节点连接到最后一个节点之后。

下面是一个简单的示例程序,它向链表中添加了三个节点,并遍历整个链表:

#include<iostream>
using namespace std;
struct Node {
  int data;
  Node* next;
};
Node* head = new Node();
void addNode(int data) {
  Node* newNode = new Node();
  newNode->data = data;
  newNode->next = NULL;
  if (head->next == NULL) // 如果链表中没有节点
    head->next = newNode;
  
  else { // 如果链表中已有节点
    Node* temp = head;
    while (temp->next != NULL)
      temp = temp->next;
    
    temp->next = newNode;
  }
}
void traverse() {
  Node* temp = head->next;
  while (temp != NULL)
    cout << temp->data << " ";
    temp = temp->next;
  
  cout << endl;
}
int main() {
  head->data = NULL;
  head->next = NULL;
  addNode(1);
  addNode(2);
  addNode(3);
  traverse();
  return 0;
}

输出结果为:

1 2 3

这表示我们成功地向链表中添加了三个节点,并遍历了整个链表。

  
  

评论区