有一个文件里面都是一行一行的数字,用空格分开,请把它每行转化成一个链表。
注意getline(ifstream, line)得到一行,而且使用了头结点。
https://gist.github.com/Jiacai/9431341
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68 |
#include <string> #include <fstream> #include <iostream> using
namespace std; struct
ListNode { int
val; ListNode *next; ListNode( int
_val) { val = _val; next = NULL; } }; /* 123 456 */ void
readFile(string fileName, ListNode** list, int
lineLimit) { ifstream ifstrm(fileName); if (!ifstrm) { exit (1); } int
i = 0; string line; while
(getline(ifstrm, line) && i < lineLimit) { // parse this line ListNode* dummy = new
ListNode(0); ListNode *last = dummy; int
idx = 0; while
(idx < line.length()) { // skip spaces while
(idx < line.length() && line[idx] == ‘ ‘ ) { idx++; } if
(idx == line.length()) break ; int
num = 0; while
(idx < line.length() && line[idx] != ‘ ‘ ) { num = num * 10 + line[idx] - ‘0‘ ; idx++; } ListNode* node = new
ListNode(num); last->next = node; last = node; } last->next = NULL; list[i] = dummy->next; delete
dummy; i++; } ifstrm.close(); } int
main() { const
int LINE_COUNT = 100; ListNode* list[LINE_COUNT]; memset (list, 0, sizeof (list)); readFile( "d:\\test.txt" , list, LINE_COUNT); for
( int i = 0; i < LINE_COUNT; i++) { ListNode* current = list[i]; if
(current == NULL) break ; while
(current != NULL) { cout << current->val << "->" ; current = current->next; } cout << "NULL"
<< endl; } system ( "pause" ); } |
原文:http://www.cnblogs.com/lautsie/p/3588733.html