Sunteți pe pagina 1din 19

Universitatea de Stat din Moldova

Facultatea de Matematică și Informatică


Departamentul Informatică

Lucrare de laborator № 3
Algoritmi, structuri de date și complexivitate
Tema: Structuri dinamice de date
Arbori, stive, cozi

A realizat: Levinschi Alexandru, IA-1702


A verificat: Novac Ludmila, doctor, conf. univ.

Chișinău – 2019
Sarcini de lucru:

Partea teoretica:
Lista este o colecție, ale cărei elemente pot fi parcurse secvențial, într-o ordine determinată. Există, deci, un
prim element, un ultim element și o modalitate de a trece de la un element al listei la cel următor. La nivel
conceptual, se poate considera că lista este o structură liniară, adică elementele unei liste sunt situate pe o
singură linie, la fel cu cele ale unui tablou unidimensional, iar ordinea naturală de parcurgere este cea în care
elementele sunt situate în listă. Deosebirea față de tablou constă în aceea că, în timp ce numarul de elemente
ale tabloului se fixează la crearea acestuia și nu mai poate fi modificat ulterior, numărul de elemente dintr-o
listă se poate modifica prin adăugări și eliminări. Tocmai din această cauză considerăm că lista este o colecție
și nu un tablou.

Listele simplu inlantuite sunt structuri de date dinamice omogene. Spre deosebire de
masive, listele nu sunt alocate ca blocuri omogene de memorie, ci ca elemente
separate de memorie. Fiecare nod al listei contine, in afara ce informatia utila, adresa
urmatorului element. Aceasta organizare permite numai acces secvential la elementele
listei.
Pentru accesarea listei trebuie cunoscuta adresa primului element (numita capul
listei); elementele urmatoare sunt accesate parcurgand lista.

Listele dublu inlantuite sunt structuri de date dinamice omogene. Ele au aceleasi
caracteristici de baza ca si listele simplu inlantuite. Diferenta fata de acestea consta in
faptul ca, pentru fiecare nod, se retine si adresa elementului anterior, ceea ce permite
traversarea listei in ambele directii.
Stiva este o structura de date logica, implementarea sa din punct de vedere fizic fiind realizata prin utilizarea
altor structuri de date.
Elementele componente ale structurii de tip stiva sunt de acelasi tip, ceea ce inseamna ca stiva este o
structura de date omogena.
Exista doua operatii de baza cu structura de tip stiva: adaugarea si extragerea unui element. Modalitatea de
implementare a operatiilor este data de disciplina de acces: LIFO – Last In First Out. Toate inserarile (push) si
extragerile (pop) sunt realizate la acelasi capat al structurii de implementare, denumit varful stivei.

Coada pastreaza caracteristicile structurii de tip stiva, mai putin aspectele de implementare a operatiilor de
inserare si extragere. Astfel, modalitatea de implementare a operatiilor este data de disciplina de acces: FIFO –
First In First Out. Toate inserarile (put) sunt efectuate la un capat al structurii de implementare fizica, iar
extragerile din coada (get) sunt realizate la celalalt capat al structurii.
In exemplul de mai jos sunt prezentate implementari ale operatiilor put si get, utilizand ca structura suport
lista simpla [...]. Structura unui element al cozii este formata dintr-o valoare de tip int si adresa nodului
succesor din structura de tip coada.

Program:
Transaction.cs

1. using System;
2. using System.Globalization;
3.
4. namespace Laborator3.Entity
5. {
6. public enum PaymentType
7. {
8. Visa,
9. Mastercard,
10. Amex
11. }
12.
13. public class Transaction
14. {
15. public int Id { get; set; }
16.
17. public DateTime DateTime { get; set; }
18.
19. public string Product { get; set; }
20.
21. public decimal Price { get; set; }
22.
23. public PaymentType PaymentType { get; set; }
24.
25. public string ClientCode { get; set; }
26.
27. public static Transaction ParseFromCsv(string line)
28. {
29. var columns = line.Split(' ');
30.
31. return new Transaction
32. {
33. Id = int.Parse(columns[0]),
34. DateTime = DateTime.Parse(columns[1] + ' ' + columns[2]),
35. Product = columns[3],
36. Price = decimal.Parse(columns[4], NumberStyles.Any, CultureInfo.InvariantCulture),
37. PaymentType = GetPaymentType(columns[5]),
38. ClientCode = columns[6]
39. };
40. }
41.
42. private static PaymentType GetPaymentType(string line)
43. {
44. switch (line)
45. {
46. case "Visa":
47. return PaymentType.Visa;
48. case "Mastercard":
49. return PaymentType.Mastercard;
50. default:
51. return PaymentType.Amex;
52. }
53. }
54.
55. public string PrintTransaction()
56. {
57. return $"{Id,-2} | " +
58. $"{DateTime.Day,-2:D2}.{DateTime.Month,-2:D2}.{DateTime.Year,-4} | " +
59. $"{DateTime.Hour,-2:D2}:{DateTime.Minute,-2:D2} | " +
60. $"{Product,-13} | " +
61. $"{Price,7} | " +
62. $"{PaymentType,-10} | " +
63. $"{ClientCode,-8}";
64. }
65. }
66. }

CSVParser.cs

1. using System.IO;
2. using System.Linq;
3. using System.Collections.Generic;
4. using Laborator3.Entity;
5.
6. namespace Laborator3.Parser
7. {
8. public static class CSVParser
9. {
10. public static List<Transaction> ProcessFile(string path)
11. {
12. var query = from line in File.ReadAllLines(path)
13. where line.Length > 1
14. select Transaction.ParseFromCsv(line);
15.
16. return query.ToList();
17. }
18. }
19. }

LinkedList.cs

1. using System;
2. using Laborator3.Entity;
3.
4. namespace Laborator3.Logic
5. {
6. public class LinkedList
7. {
8. public Node head;
9.
10. public class Node
11. {
12. public Transaction data;
13. public Node next;
14.
15. public Node(Transaction data)
16. {
17. this.data = data;
18. next = null;
19. }
20. }
21.
22. public void Push(Transaction newData)
23. {
24. Node newNode = new Node(newData);
25. newNode.next = head;
26. head = newNode;
27. }
28.
29. public void InsertAfter(Node previous, Transaction newData)
30. {
31. if (previous == null)
32. {
33. Console.WriteLine("The given previous node cannot be null.");
34. return;
35. }
36.
37. Node newNode = new Node(newData);
38. newNode.next = previous.next;
39. previous.next = newNode;
40. }
41.
42. public void Append(Transaction newData)
43. {
44. Node newNode = new Node(newData);
45.
46. if (head == null)
47. {
48. head = new Node(newData);
49. return;
50. }
51.
52. newNode.next = null;
53. Node last = head;
54. while (last.next != null)
55. last = last.next;
56.
57. last.next = newNode;
58. }
59.
60. public Transaction FirstOrDefault(Node head, int id)
61. {
62. if (head == null)
63. return null;
64.
65. if (head.data.Id == id)
66. return head.data;
67.
68. return FirstOrDefault(head.next, id);
69. }
70.
71. public void Delete(int id)
72. {
73. Node temp = head, prev = null;
74.
75. if (temp != null && temp.data.Id == id)
76. {
77. head = temp.next;
78. return;
79. }
80.
81. while (temp != null && temp.data.Id != id)
82. {
83. prev = temp;
84. temp = temp.next;
85. }
86.
87. if (temp == null)
88. return;
89.
90. prev.next = temp.next;
91. }
92.
93. public void PrintList()
94. {
95. Node node = head;
96. while (node != null)
97. {
98. Console.WriteLine(node.data.PrintTransaction());
99. node = node.next;
100. }
101. }
102. }
103. }

DoublyLinkedList.cs

1. using System;
2. using Laborator3.Entity;
3.
4. namespace Laborator3.Logic
5. {
6. public class DoublyLinkedList
7. {
8. public Node head;
9.
10. public class Node
11. {
12. public Transaction data;
13. public Node previous;
14. public Node next;
15.
16. public Node(Transaction data)
17. {
18. this.data = data;
19. }
20. }
21.
22. public void Push(Transaction newData)
23. {
24. Node newNode = new Node(newData);
25. newNode.next = head;
26. newNode.previous = null;
27.
28. if (head != null)
29. head.previous = newNode;
30.
31. head = newNode;
32. }
33.
34. public void InsertAfter(Node previous, Transaction newData)
35. {
36. if (previous == null)
37. {
38. Console.WriteLine("The given previous node cannot be null.");
39. return;
40. }
41.
42. Node newNode = new Node(newData);
43. newNode.next = previous.next;
44. previous.next = newNode;
45. newNode.previous = previous;
46.
47. if (newNode.next != null)
48. newNode.next.previous = newNode;
49. }
50.
51. public void Append(Transaction newData)
52. {
53. Node newNode = new Node(newData);
54. Node last = head;
55.
56. newNode.next = null;
57.
58. if (head == null)
59. {
60. newNode.previous = null;
61. head = newNode;
62. return;
63. }
64.
65. while (last.next != null)
66. last = last.next;
67.
68. last.next = newNode;
69.
70. newNode.previous = last;
71. }
72.
73. public void DeleteNode(Node headRef, Node del)
74. {
75. if (headRef == null || del == null)
76. return;
77.
78. if (headRef == del)
79. headRef = del.next;
80.
81. if (del.next != null)
82. del.next.previous = del.previous;
83.
84. if (del.previous != null)
85. del.previous.next = del.next;
86. }
87.
88. public void DeleteAtIndex(Node headRef, int id)
89. {
90. if (headRef == null || id <= 0)
91. return;
92.
93. Node current = headRef;
94.
95. for (int i = 0; current != null && i < id; i++)
96. current = current.next;
97.
98. if (current == null)
99. return;
100.
101. DeleteNode(headRef, current);
102. }
103.
104. public Transaction FirstOrDefault(Node head, int id)
105. {
106. if (head == null)
107. {
108. return null;
109. }
110.
111. if (head.data.Id == id)
112. return head.data;
113.
114. return FirstOrDefault(head.next, id);
115. }
116.
117. public void PrintList(Node node)
118. {
119. Node last = null;
120. while (node != null)
121. {
122. Console.WriteLine(node.data.PrintTransaction());
123. last = node;
124. node = node.next;
125. }
126. }
127. }
128. }

CircularLinkedList.cs

1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. using System.Threading.Tasks;
6. using Laborator3.Entity;
7.
8. namespace Laborator3.Logic
9. {
10. public class CircularLinkedList
11. {
12. public class Node
13. {
14. public Transaction data;
15. public Node next;
16. }
17.
18. public static Node Push(Node head, Transaction data)
19. {
20. Node node = new Node();
21. Node temp = head;
22. node.data = data;
23. node.next = head;
24.
25. if (head != null)
26. {
27. while (temp.next != head)
28. temp = temp.next;
29. temp.next = node;
30. }
31. else
32. {
33. node.next = node;
34. }
35.
36. head = node;
37.
38. return head;
39. }
40.
41. public static Transaction FirstOrDefault(Node head, int id)
42. {
43. if (head == null)
44. return null;
45.
46. if (head.data.Id == id)
47. return head.data;
48.
49. return FirstOrDefault(head.next, id);
50. }
51.
52. public static Node DeleteNode(Node head, int id)
53. {
54. if (head == null)
55. return null;
56.
57. Node current = head, previous = new Node();
58. while (current.data.Id != id)
59. {
60. if (current.next == head)
61. {
62. Console.WriteLine("Not found!");
63. break;
64. }
65.
66. previous = current;
67. current = current.next;
68. }
69.
70. if (current.next == head)
71. {
72. head = null;
73. return head;
74. }
75.
76. if (current == head)
77. {
78. previous = head;
79. while (previous.next != head)
80. {
81. previous = previous.next;
82. }
83.
84. head = current.next;
85. previous.next = head;
86. }
87. else if (current.next == head)
88. previous.next = head;
89. else
90. previous.next = current.next;
91.
92. return head;
93. }
94.
95. public static void PrintList(Node head)
96. {
97. Node temp = head;
98. if (head != null)
99. {
100. do
101. {
102. Console.WriteLine(temp.data.PrintTransaction());
103. temp = temp.next;
104. }
105. while (temp != head);
106. }
107. }
108. }
109. }

Stack.cs

1. using System;
2.
3. namespace Laborator3.Logic
4. {
5. public class Stack<T>
6. {
7. private StackNode<T> top;
8. private int size;
9.
10. private class StackNode<T>
11. {
12. private T value;
13. private StackNode<T> next;
14.
15. public StackNode(T value)
16. {
17. this.value = value;
18. }
19.
20. public T GetValue()
21. {
22. return value;
23. }
24.
25. public StackNode<T> GetNext()
26. {
27. return next;
28. }
29.
30. public void SetNext(StackNode<T> nextNode)
31. {
32. this.next = nextNode;
33. }
34. }
35.
36. public void Push(T value)
37. {
38. StackNode<T> current = new StackNode<T>(value);
39. current.SetNext(top);
40. top = current;
41. size++;
42. }
43.
44. public T Peek()
45. {
46. CheckNotEmpty();
47. return top.GetValue();
48. }
49.
50. public T Pop()
51. {
52. CheckNotEmpty();
53. T pop = top.GetValue();
54. top = top.GetNext();
55. size--;
56. return pop;
57. }
58.
59. public void Clear()
60. {
61. top = null;
62. size = 0;
63. }
64.
65. public int Size()
66. {
67. return size;
68. }
69.
70. public bool IsEmpty()
71. {
72. return size == 0;
73. }
74.
75. private void CheckNotEmpty()
76. {
77. if (size == 0)
78. throw new Exception();
79. }
80. }
81. }

Queue.cs

1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Text;
5. using System.Threading.Tasks;
6.
7. namespace Laborator3.Logic
8. {
9. public class Queue<T> where T : class
10. {
11. private QueueNode<T> first;
12. private QueueNode<T> last;
13. private int size;
14.
15. public class QueueNode<T>
16. {
17. private T value;
18. private QueueNode<T> next;
19.
20. public QueueNode(T value)
21. {
22. this.value = value;
23. this.next = null;
24. }
25.
26. public void SetNext(QueueNode<T> nextNode)
27. {
28. next = nextNode;
29. }
30.
31. public QueueNode<T> GetNext()
32. {
33. return next;
34. }
35.
36. public T GetValue()
37. {
38. return value;
39. }
40. }
41.
42. public void Offer(T value)
43. {
44. QueueNode<T> current = new QueueNode<T>(value);
45. if (size == 0)
46. {
47. current.SetNext(first);
48. first = current;
49. last = current;
50. size++;
51. return;
52. }
53.
54. last.SetNext(current);
55. last = current;
56. size++;
57. }
58.
59. public T Peek()
60. {
61. if (!IsEmpty())
62. {
63. return first.GetValue();
64. }
65. else
66. {
67. return null;
68. }
69. }
70.
71. public QueueNode<T> Poll()
72. {
73. if (IsEmpty())
74. return null;
75.
76. QueueNode<T> current = first;
77. first = first.GetNext();
78. size--;
79. return current;
80. }
81.
82. public bool IsEmpty()
83. {
84. return size == 0;
85. }
86.
87. public void Clear()
88. {
89. size = 0;
90. first = null;
91. last = null;
92. }
93.
94. public int Size()
95. {
96. return size;
97. }
98. }
99. }

Program.cs

1. using System;
2. using Laborator3.Entity;
3. using Laborator3.Logic;
4. using Laborator3.Parser;
5.
6. namespace Laborator3
7. {
8. internal class Program
9. {
10. private static void Main(string[] args)
11. {
12. var transactions = CSVParser.ProcessFile("..\\..\\CSV Files\\transactions.csv");
13.
14. #region Linked List
15.
16. Console.WriteLine("----- Linked List -----");
17. var linkedList = new LinkedList();
18.
19. foreach (var transaction in transactions)
20. {
21. linkedList.Append(transaction);
22. }
23.
24. linkedList.InsertAfter(linkedList.head, transactions[24]);
25. linkedList.Push(transactions[29]);
26. linkedList.Delete(30);
27.
28. linkedList.PrintList();
29.
30. Console.WriteLine();
31.
32. Console.WriteLine(linkedList.FirstOrDefault(linkedList.head, 25).PrintTransaction());
33.
34. #endregion
35.
36. #region Doubly Linked List
37.
38. Console.WriteLine("----- Doubly Linked List -----");
39. var doublyLinkedList = new DoublyLinkedList();
40.
41. foreach (var transaction in transactions)
42. {
43. doublyLinkedList.Append(transaction);
44. }
45.
46. doublyLinkedList.InsertAfter(doublyLinkedList.head, transactions[24]);
47. doublyLinkedList.DeleteAtIndex(doublyLinkedList.head, 1);
48.
49. doublyLinkedList.PrintList(doublyLinkedList.head);
50.
51. Console.WriteLine();
52.
53. Console.WriteLine(doublyLinkedList.FirstOrDefault(doublyLinkedList.head, 25).PrintTransac
tion());
54.
55. #endregion
56.
57. #region Circular Linked List
58.
59. Console.WriteLine("----- Circular Linked List -----");
60. CircularLinkedList.Node circular = null;
61.
62. for (int i = transactions.Count - 1; i > -1; i--)
63. {
64. circular = CircularLinkedList.Push(circular, transactions[i]);
65. }
66.
67. circular = CircularLinkedList.Push(circular, transactions[24]);
68. circular = CircularLinkedList.DeleteNode(circular, 25);
69.
70. CircularLinkedList.PrintList(circular);
71.
72. Console.WriteLine();
73.
74. Console.WriteLine(CircularLinkedList.FirstOrDefault(circular, 25).PrintTransaction());
75.
76. #endregion
77.
78. #region Stack
79.
80. Stack<Transaction> stack = new Stack<Transaction>();
81.
82. stack.Push(transactions[0]);
83. stack.Push(transactions[9]);
84. stack.Push(transactions[49]);
85.
86. Console.WriteLine(stack.Peek().PrintTransaction());
87.
88. Console.WriteLine(stack.Pop().PrintTransaction());
89. Console.WriteLine(stack.Pop().PrintTransaction());
90. Console.WriteLine(stack.Pop().PrintTransaction());
91.
92. try
93. {
94. Console.WriteLine(stack.Pop().PrintTransaction());
95. }
96. catch (Exception e)
97. {
98. Console.WriteLine("Empty stack!");
99. }
100.
101. stack.Push(transactions[24]);
102. Console.WriteLine(stack.Peek().PrintTransaction());
103.
104. #endregion
105.
106. #region Queue
107.
108. Queue<Transaction> queue = new Queue<Transaction>();
109.
110. queue.Offer(transactions[0]);
111. queue.Offer(transactions[9]);
112. queue.Offer(transactions[49]);
113.
114. Console.WriteLine(queue.Peek().PrintTransaction());
115.
116. Console.WriteLine(queue.Poll().GetValue().PrintTransaction());
117. Console.WriteLine(queue.Poll().GetValue().PrintTransaction());
118. Console.WriteLine(queue.Poll().GetValue().PrintTransaction());
119.
120. #endregion
121. }
122. }
123. }

transactions.csv
1 02/01/2018 12:55 Bag 481.81 Visa PBF6ALJT
2 09/01/2018 11:10 Scotch_Tape 278.30 Mastercard RPM68I6E
3 11/01/2018 13:15 Shampoo 481.27 Visa UXQDVF69
4 26/01/2018 14:15 Money 551.30 Visa YDMVHTUN
5 12/02/2018 11:15 Milk 434.32 Mastercard 3WXRJW29
6 15/02/2018 10:10 Picture_Frame 158.53 Mastercard DUJX6JBS
7 19/02/2018 12:25 Knife 75.73 Amex 4OH9Y293
8 27/02/2018 16:40 Thread 560.13 Visa NGRZTEGE
9 08/03/2018 13:10 Tissue_Box 1166.66 Amex 3WK9QGB2
10 14/03/2018 09:20 Conditioner 242.35 Visa FBSW08OH
11 19/03/2018 14:50 Model_Car 280.29 Mastercard 8GVGZGSF
12 20/03/2018 14:30 Rubber_Band 1261.39 Mastercard YJ4V9SB9
13 21/03/2018 13:55 Watch 712.50 Visa 67CK3KK2
14 29/03/2018 16:05 Seat_Belt 1048.24 Amex UNHJ1F78
15 04/04/2018 11:25 Drawer 1273.85 Mastercard KQ2DIP6V
16 09/04/2018 17:00 Spoon 1471.03 Amex ZDEG2FFX
17 16/04/2018 15:30 Nail_File 1063.94 Visa HQ8QWFWP
18 17/04/2018 10:05 Sailboat 104.76 Visa LNLZ2BMH
19 19/04/2018 09:35 Nail_File 707.95 Mastercard 8BGTVBG9
20 01/05/2018 10:55 Sofa 71.75 Visa 5U4UPEX1
21 10/05/2018 15:10 Nail_File 1284.06 Visa JZJM6Q87
22 15/05/2018 10:20 Balloon 35.63 Visa GOCH0AWI
23 16/05/2018 14:35 Clothes 787.12 Mastercard 6WIZGWPL
24 21/05/2018 10:40 Seat_Belt 1486.80 Amex S0EQLF92
25 28/05/2018 11:00 Mouse_Pad 1120.41 Visa QHUQG0Y3
26 08/06/2018 13:25 Vase 281.29 Mastercard NLC9252N
27 12/06/2018 10:15 Blouse 1047.68 Visa IBLQNEEZ
28 13/06/2018 13:30 Socks 1276.40 Amex UUSYNWN3
29 25/06/2018 12:50 Tooth_Picks 756.52 Visa 5XN53DRU
30 26/06/2018 14:45 Charger 425.86 Mastercard PB1D44V4
31 29/06/2018 11:40 Sharpie 234.93 Visa RFIVCZEK
32 19/07/2018 12:30 Knife 350.65 Amex WGGF74OV
33 02/08/2018 12:45 Keyboard 674.05 Visa ROO03D9L
34 08/08/2018 15:40 Sailboat 148.98 Amex 8P5BY1NI
35 10/08/2018 15:15 Air_Freshener 492.28 Visa QU1DJTS2
36 04/09/2018 13:20 Candy_Wrapper 683.50 Mastercard NCMQJP02
37 14/09/2018 09:25 White_Out 467.51 Visa EDIMXBP2
38 21/09/2018 13:05 Key_Chain 560.09 Amex XUEPW4QK
39 31/10/2018 16:30 Bookmark 151.06 Mastercard 4YE4E92N
40 01/11/2018 16:45 iPod 101.54 Visa GTQBVSFD
41 05/11/2018 16:35 Flowers 427.23 Mastercard ZFMUD120
42 29/11/2018 16:15 Video_Games 125.01 Visa ZSP1AQAO
43 30/11/2018 14:20 Pen 667.91 Visa O1KZTM06
44 04/12/2018 09:30 Candle 523.81 Amex ECOATKS8
45 17/12/2018 12:35 Sand_Paper 178.41 Visa UJ9LMTH4
46 14/01/2019 14:10 Twezzers 576.82 Amex 0TY6SATV
47 21/01/2019 09:00 Pool_Stick 409.71 Mastercard 5TLIM3KE
48 23/01/2019 09:55 Sand_Paper 637.44 Visa VBYXF0SX
49 30/01/2019 15:35 Sandal 249.36 Amex HB4XCUHI
50 04/02/2019 11:45 Vase 95.81 Mastercard P8M9H3SN
Rezultatele rularii programului: Lista simplu inlantuita
Lista dublu inlantuita
Lista circular inlantuita
Stiva

Coada

S-ar putea să vă placă și