Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <fstream>
- using namespace std;
- typedef struct Node ListNode;
- struct Node {
- int data;
- ListNode *next;
- };
- typedef struct FirstNode *LinkedList;
- struct FirstNode {
- ListNode *first;
- };
- LinkedList newList(const char *filename);
- ListNode newListNode(int v);
- void printList(LinkedList l);
- void addFirst(LinkedList l, int v);
- void addLast(LinkedList l, int v);
- void removeFirst(LinkedList l);
- int findIndex(LinkedList l, int v);
- LinkedList newList(const char *filename) {
- ifstream infile(filename);
- char numb;
- LinkedList list = new FirstNode;
- if (infile) {
- list->first = NULL;
- while (true) {
- infile >> numb;
- if (!infile.eof()) {
- addLast(list, (int)(numb - '0'));
- }
- else {
- break;
- }
- }
- } else {
- cout << "Can't open file\n";
- }
- return list;
- }
- ListNode newListNode(int v) {
- static ListNode node;
- node.data = v;
- node.next = NULL;
- return node;
- }
- void printList(LinkedList l) {
- ListNode* node = l->first;
- while (node != NULL) {
- cout << node->data << ' ';
- node = node->next;
- }
- }
- void addFirst(LinkedList l, int v) {
- ListNode* newFirst = new ListNode;
- newFirst->data = v;
- newFirst->next = NULL;
- newFirst->next = l->first;
- l->first = newFirst;
- }
- void addLast(LinkedList l, int v) {
- ListNode* newLast = &newListNode;
- ListNode* node = l->first;
- if (node != NULL) {
- while (node->next != NULL) {
- node = node->next;
- }
- node->next = newLast;
- }
- else {
- l->first = newLast;
- }
- }
- void removeFirst(LinkedList l) {
- ListNode* first = l->first;
- ListNode* second = first->next;
- first->next = NULL;
- l->first = second;
- }
- int findIndex(LinkedList l, int v) {
- int i = 0;
- ListNode* node = l->first;
- while (node != NULL) {
- if (node->data == v) {
- return i;
- }
- node = node->next;
- i++;
- }
- return -1;
- }
- int main()
- {
- LinkedList list = new FirstNode;
- list = newList("abc.txt");
- addLast(list, 3);
- removeFirst(list);
- addFirst(list, 2);
- printList(list);
- cout << newListNode(5).data;
- cout << ' ' << findIndex(list, 0);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement