C ++程序实现单链接列表

单链接列表是一种数据结构,由使用自引用结构创建的节点组成。这些节点中的每一个都包含两个部分,即数据和对下一个列表节点的引用。访问整个链接列表仅需要引用第一个列表节点。这被称为头部。列表中的最后一个节点没有指向任何内容,因此它在该部分中存储NULL。

给出实现单链表的程序如下。

示例

#include <iostream>

using namespace std;

struct Node {

   int data;

   struct Node *next;

};

struct Node* head = NULL;

void insert(int new_data) {

   struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));

   new_node->data = new_data;

   new_node->next = head;

   head = new_node;

}

void display() {

   struct Node* ptr;

   ptr = head;

   while (ptr != NULL) {

      cout<< ptr->data <<" ";

      ptr = ptr->next;

   }

}

int main() {

   insert(3);

   insert(1);

   insert(7);

   insert(2);

   insert(9);

   cout<<"The linked list is: ";

   display();

   return 0;

}

输出结果

The linked list is: 9 2 7 1 3

在上述程序中,结构Node构成了链表节点。它包含数据和指向下一个链接列表节点的指针。给出如下。

struct Node {

   int data;

   struct Node *next;

};

该函数insert()将数据插入到链表的开头。它创建一个new_node并将数字插入new_node的数据字段中。然后new_node指向头部。最后,头是new_node,即链接列表从此处开始。这在下面给出。

void insert(int new_data) {

   struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));

   new_node->data = new_data;

   new_node->next = head;

   head = new_node;

}

该功能display()显示整个链表。第一点指向头。然后将其连续转发到下一个节点,直到打印出节点的所有数据值为止。这在下面给出。

void display() {

   struct Node* ptr;

   ptr = head;

   while (ptr != NULL) {

      cout<< ptr->data <<" ";

      ptr = ptr->next;

   }

}

在函数中main(),首先通过调用将各种值插入到链表中insert()。然后显示链接列表。这在下面给出。

int main() {

   insert(3);

   insert(1);

   insert(7);

   insert(2);

   insert(9);

   cout<<"The linked list is: ";

   display();

   return 0;

}

以上是 C ++程序实现单链接列表 的全部内容, 来源链接: utcz.com/z/316675.html

回到顶部