C
C#2mo ago
avishy

Queue and Node question

public static bool EqualSums(Queue<int> q) { int first = q.Remove(); int last = RemoveLast(q); int sum = first + last; Queue<int> c = q; for(int i = 0; i < Length(q)/2; i++) { if(q.Remove() + RemoveLast(q) != sum) { return false; } } if(!q.IsEmpty() && q.Remove() != sum) { return false; } return true; } public static void RemoveEqualSums(Node<Queue<int>> lst) { Node<Queue<int>> curr = lst; if (EqualSums(curr.GetValue()) == false) { curr.SetNext(null); } while (curr.GetNext() != null) { if(EqualSums(curr.GetNext().GetValue()) ==false) { curr.SetNext(curr.GetNext().GetNext()); curr.GetNext().SetNext(null); } curr = curr.GetNext();
} } why is this code incorrect? please help
1 Reply
contione
contione2mo ago
public static bool EqualSums(Queue<int> q) { // Helper method to remove and return the last element of the queue static int RemoveLast(Queue<int> q) { int last; Queue<int> temp = new Queue<int>(); while (q.Count > 1) { temp.Enqueue(q.Dequeue()); } last = q.Dequeue(); // The last element while (temp.Count > 0) { q.Enqueue(temp.Dequeue()); } return last; } // Make a copy of the queue Queue<int> copy = new Queue<int>(q); int first = copy.Dequeue(); int last = RemoveLast(copy); int sum = first + last; // Verify sums in the remaining elements while (copy.Count > 1) { int front = copy.Dequeue(); int back = RemoveLast(copy); if (front + back != sum) { return false; } } // If there's one element left, check if it equals the required sum if (copy.Count == 1 && copy.Dequeue() != sum) { return false; } return true; } public static void RemoveEqualSums(Node<Queue<int>> lst) { Node<Queue<int>> curr = lst; while (curr != null && curr.GetNext() != null) { if (!EqualSums(curr.GetNext().GetValue())) { curr.SetNext(curr.GetNext().GetNext()); } else { curr = curr.GetNext(); } } } // Assume Node class definition with appropriate methods public class Node<T> { private T value; private Node<T> next; public Node(T value) { this.value = value; this.next = null; } public T GetValue() { return value; } public Node<T> GetNext() { return next; } public void SetNext(Node<T> next) { this.next = next; } }