Good afternoon, this task:
Write a class that implements a single-linked list. The class must contain the methods Push (add an element to the top of the list), Pop (extract an element from the beginning of the list). It must also override the inherited Print method, which returns a string representation of the list. Write a Reverse method reversing the order of the elements in the list. Write a program using the class.
The problem is in the reverse method. How I did:
public void Reverse() { if (head == null) throw new ListUnderflow(); StringBuilder PrintList = new StringBuilder(); Node temp = head; while (temp != null) { PrintList.Append(temp.value); PrintList.Append(" "); temp = temp.next; } StringBuilder builder = new StringBuilder(); for (int i = PrintList.Length - 1; i >= 0; i--) { builder.Append(PrintList[i]); } string newName = builder.ToString(); Console.WriteLine(newName); } but it’s not so true, as I was told that it was necessary not to display on the screen, but to create a new list, then call pop, and push there, and what method should return then? new list? like this:
public SinglyLinkedList Reverse() { if (head == null) throw new ListUnderflow(); SinglyLinkedList l2 = new SinglyLinkedList(); l2.Push(Pop()); return l2; } but I'm not sure about this turned here, can you tell?
reversemethod does not create a new element. And changes the original. In some implementations, it generally does not change anything in the container itself, but simply sets a flag that it takes into account in other operations. - pavel