首页 > 其他 > 详细

将数字文件转成链表

时间:2014-03-09 01:30:03      阅读:519      评论:0      收藏:0      [点我收藏+]

有一个文件里面都是一行一行的数字,用空格分开,请把它每行转化成一个链表。

注意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");
}

  

将数字文件转成链表,布布扣,bubuko.com

将数字文件转成链表

原文:http://www.cnblogs.com/lautsie/p/3588733.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!