example201.cpp

来自「Data Abstraction & Problem Solving with 」· C++ 代码 · 共 55 行

CPP
55
字号
#include <iostream>#include <fstream>#include <string>using namespace std;struct Node{  int item;   Node *next;}; // end structint main(){   string fileName = "numbers.txt";   Node *head = NULL, *tail = NULL;	// Creates a linked list from the data in a text 	// file. The pointer variables head and tail are	// initially NULL. fileName is a string that names	// an existing external text file.	ifstream inFile(fileName);	int      nextItem;	if (inFile >> nextItem)               // is file empty?	{  // file not empty:	   head = new Node;	   // add the first integer to the list	   head->item = nextItem;	   head->next = NULL;	   tail = head;	   // add remaining integers to linked list	   while (inFile >> nextItem)	   {  tail->next = new Node;	      tail = tail->next;	      tail->item = nextItem;	      tail->next = NULL;	   }  // end while	}  // end if	inFile.close();	// Assertion: head points to the first node of the	// created linked list; tail points to the last	// node. If the file is empty, head and tail are	// NULL (list is empty).   // traverse the list to the end, writing each item   for (Node *cur = head; cur != NULL; cur = cur->next)      cout << cur->item << " ";   cout << endl;   return 0;}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?