Advertisement
Guest User

Untitled

a guest
Sep 22nd, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. using namespace std;
  4.  
  5. typedef struct Node ListNode;
  6. struct Node {
  7. int data;
  8. ListNode *next;
  9. };
  10. typedef struct FirstNode *LinkedList;
  11. struct FirstNode {
  12. ListNode *first;
  13. };
  14.  
  15. LinkedList newList(const char *filename);
  16. ListNode newListNode(int v);
  17. void printList(LinkedList l);
  18. void addFirst(LinkedList l, int v);
  19. void addLast(LinkedList l, int v);
  20. void removeFirst(LinkedList l);
  21. int findIndex(LinkedList l, int v);
  22.  
  23. LinkedList newList(const char *filename) {
  24. ifstream infile(filename);
  25. char numb;
  26. LinkedList list = new FirstNode;
  27. if (infile) {
  28. list->first = NULL;
  29.  
  30. while (true) {
  31. infile >> numb;
  32. if (!infile.eof()) {
  33. addLast(list, (int)(numb - '0'));
  34. }
  35. else {
  36. break;
  37. }
  38. }
  39. } else {
  40. cout << "Can't open file\n";
  41. }
  42. return list;
  43. }
  44. ListNode newListNode(int v) {
  45. static ListNode node;
  46. node.data = v;
  47. node.next = NULL;
  48. return node;
  49. }
  50. void printList(LinkedList l) {
  51. ListNode* node = l->first;
  52. while (node != NULL) {
  53. cout << node->data << ' ';
  54. node = node->next;
  55. }
  56. }
  57. void addFirst(LinkedList l, int v) {
  58. ListNode* newFirst = new ListNode;
  59. newFirst->data = v;
  60. newFirst->next = NULL;
  61. newFirst->next = l->first;
  62. l->first = newFirst;
  63. }
  64. void addLast(LinkedList l, int v) {
  65. ListNode* newLast = &newListNode;
  66. ListNode* node = l->first;
  67. if (node != NULL) {
  68. while (node->next != NULL) {
  69. node = node->next;
  70. }
  71. node->next = newLast;
  72. }
  73. else {
  74. l->first = newLast;
  75. }
  76. }
  77. void removeFirst(LinkedList l) {
  78. ListNode* first = l->first;
  79. ListNode* second = first->next;
  80. first->next = NULL;
  81. l->first = second;
  82. }
  83. int findIndex(LinkedList l, int v) {
  84. int i = 0;
  85. ListNode* node = l->first;
  86. while (node != NULL) {
  87. if (node->data == v) {
  88. return i;
  89. }
  90. node = node->next;
  91. i++;
  92. }
  93. return -1;
  94. }
  95. int main()
  96. {
  97. LinkedList list = new FirstNode;
  98. list = newList("abc.txt");
  99. addLast(list, 3);
  100. removeFirst(list);
  101. addFirst(list, 2);
  102. printList(list);
  103. cout << newListNode(5).data;
  104. cout << ' ' << findIndex(list, 0);
  105. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement