C++ linked list

本文介绍了一种使用C++构建链表的方法,包括正向构建和反向构建两种方式,并展示了如何通过输入一系列整数来创建链表。此外,还提供了完整的代码示例和运行结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//C++: linked list
#include <iostream>
#include <cstdlib> // for system("PAUSE")
#include <iomanip>
using namespace std;

struct nodeType {
   int info;
   nodeType* link;
}; // 不要忘了分号
nodeType* buidListForward();
nodeType* buildListBackward();

int main() {
   nodeType* head;
   nodeType* current;
   head = buildListBackward();
   current = head;
   cout << "list = ";

   int count = 0;
   while(current != NULL) {
       cout << setw(5) << current -> info;
       count++;
       if(count % 10 == 0)
          cout << endl;
       current = current -> link;

   }

   system("PAUSE");
   return 0;
}

//build a linked list forward
nodeType* buildListForward() {
   nodeType *first, *last, *newNode;
   int num;
   cout << "Enter a list of integers ending with -999"
        << endl;
   cin >> num;
   first = NULL;
   while (num != -999) {
      newNode = new nodeType;
      newNode -> info = num;
      newNode -> link = NULL;

   //insert the new node
   if(first == NULL) {
      first = newNode;
      last = newNode;
   }
   else {
      newNode -> link = first;
      first = newNode;
   }
   cin >> num;
   }
   return first;

}


//build a list backward
nodeType* buildListBackward() {
   nodeType *first, *newNode;
   int num;
   cout << "Enter a list of integers ending with -999"
        << endl;
   cin >> num;
   first = NULL;

   while (num != -999) {
      newNode = new nodeType;
      newNode -> info = num;
      newNode -> link = first;

      first = newNode;
      cin >> num;
   }
   return first;

}



运行结果如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值