Why is my C# Array changing without anything being assigned to it? - c#

I have a small winforms program for a task which is to create a Recipe book. The application has two windows, but my bug pertains to only one.
I have two main classes: Recipe.cs and RecipeManager.cs, the idea is that the RecipeManager holds an array of Recipes. (For this task we weren't allowed to use Linq or ArrayLists)
Now, when I fill in the form and click "Add Recipe", the first one works successfully and the listBox populates correctly, however the second time I "Add Recipe" the recipeList array seems to get rewritten with the new Recipe entirely, and I have no idea why this is happening. The recipeList seems to change before my Add method even adds it to the array!
See gif of problem in question:
https://i.imgur.com/sIMICcG.gifv
Recipe.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
namespace programmingTask4
{
public class Recipe
{
private string[] ingredientArray;
private string name;
private FoodCategory category;
private string description;
private const int maxNumOfIngredients = 20;
public string Name
{
get { return name; }
set { name = value; }
}
public FoodCategory Category
{
get { return category; }
set { category = value; }
}
public string Description
{
get { return description; }
set { description = value; }
}
public string[] Ingredient
{
get { return ingredientArray; }
set { ingredientArray = value; }
}
public int MaxNumOfIngredients
{
get { return ingredientArray.Length; }
}
public Recipe(int maxNumOfIngredients)
{
Console.WriteLine("Recipe constructor was called!");
ingredientArray = new string[maxNumOfIngredients];
DefaultValues();
}
public void DefaultValues()
{
for (int i = 0; i < ingredientArray.Length; i++)
{
ingredientArray[i] = string.Empty;
name = string.Empty;
category = FoodCategory.Vegetarian;
description = string.Empty;
}
}
public int FindVacantPosition()
{
int results;
for (int i = 0; i < ingredientArray.Length; i++)
{
if(ingredientArray[i] == string.Empty)
{
results = i;
return results;
}
}
return -1;
}
public bool AddIngredient(string value)
{
bool ok;
int next = FindVacantPosition();
if(next >= 0)
{
ok = true;
ingredientArray[next] = value;
}
else {
ok = false ;
}
return ok;
}
public bool CheckIndex(int index)
{
bool check = false;
if(index <= ingredientArray.Length && index >= 0)
{
check = true;
}
return check;
}
public int GetCurrentNumOfIngredients()
{
int count = 0;
for (int i = 0; i < ingredientArray.Length; i++)
{
if (!string.IsNullOrEmpty(ingredientArray[i]))
{
count++;
}
}
return count;
}
public override string ToString()
{
int chars = Math.Min(description.Length, 15);
string descriptionText = description.Substring(0, chars);
if (string.IsNullOrEmpty(descriptionText))
descriptionText = "NO DESCRIPTION";
string textOut = string.Format("{0, -20} {1,4} {2,-12} {3,-15}", name, GetCurrentNumOfIngredients(), category.ToString(), descriptionText);
return textOut;
}
public bool ChangeIngredientAt(int index, string value)
{
bool bok = true;
if (CheckIndex(index))
ingredientArray[index] = value;
else
bok = false;
return bok;
}
public bool DeleteIngredientAt(int index)
{
bool bok = true;
if (CheckIndex(index))
ingredientArray[index] = "NO DESCRIPTION";
else
bok = false;
return bok;
}
}
}
RecipeManager.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace programmingTask1
{
class RecipeManager
{
private Recipe[] recipeList;
public RecipeManager(int maxNumOfElements)
{
Console.WriteLine("Recipe manager constructor called!");
recipeList = new Recipe[maxNumOfElements];
}
private int FindVacantPosition()
{
for (int i = 0; i < recipeList.Length; i++)
{
if (recipeList[i] == null)
{
Console.WriteLine("Found free position at: " + i);
return i;
}
}
return -1;
}
public bool CheckIndex(int index)
{
bool check = false;
if (index <= recipeList.Length && index >= 0)
{
check = true;
}
return check;
}
public Recipe GetRecipeAt(int index)
{
if (CheckIndex(index))
return recipeList[index];
else
return null;
}
public bool Add(Recipe newRecipe)
{
if (newRecipe == null)
return false;
bool ok;
int next = FindVacantPosition();
if (next >= 0)
{
ok = true;
Console.WriteLine("Setting recipe list at index " + next + " to " + newRecipe.ToString());
recipeList[next] = newRecipe;
}
else
{
Console.WriteLine("No space for recipe available! " + next);
ok = false;
}
return ok;
}
public int CurrentNumberofItems()
{
int num = 0;
for (int i = 0; i < recipeList.Length; i++)
{
if (recipeList[i] != null)
{
num++;
}
}
return num;
}
public string[] RecipeListToString()
{
string[] results = new string[recipeList.Length];
for (int i = 0; i < recipeList.Length; i++)
{
if (recipeList[i] != null)
results[i] = recipeList[i].ToString();
else
results[i] = string.Empty;
}
return results;
}
}
}
FormMain.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace programmingTask4
{
public partial class FormMain : Form
{
const int maxRecipe = 3;
const int maxIngredients = 20;
Recipe currRecipe = new Recipe(maxIngredients);
RecipeManager recipemanager = new RecipeManager(maxRecipe);
public FormMain()
{
Console.WriteLine("Form constructor was called!");
InitializeComponent();
InitializeGui();
}
public void InitializeGui()
{
comboBoxCategory.DataSource = Enum.GetValues(typeof(FoodCategory));
}
public void UpdateGUI()
{
//listBoxDisplay.Text = recipemanager.CurrentNumberofItems().ToString();
//listBoxDisplay.Text = currRecipe.Ingredient.ToString();
string[] recipeListStrings = recipemanager.RecipeListToString();
listBoxDisplay.Items.Clear();
listBoxDisplay.Items.AddRange(recipeListStrings);
}
private void buttonRecipe_Click(object sender, EventArgs e)//add recipe button
{
currRecipe.Category = (FoodCategory)comboBoxCategory.SelectedIndex;
currRecipe.Name = textBoxRecipeName.Text.Trim();
currRecipe.Description = richTextBoxDescription.Text.Trim();
Console.WriteLine("Adding recipe: " + currRecipe.ToString());
bool result = recipemanager.Add(currRecipe);
Console.WriteLine("Result was " + result + " for adding to recipe list");
UpdateGUI();
currRecipe.DefaultValues();
}
}
}

Recipe is a class, which mean it's a reference type.
In your main form, your currRecipe instance is never changed.
RecipeManager has an array to store references of instance but unfortunately it stores the same instance because of 2.
Since RecipeManager stores the same instance of currRecipe, any modification on currRecipe would display N times.
To prevent it. Modify your buttonRecipe_Click
private void buttonRecipe_Click(object sender, EventArgs e)//add recipe button
{
currRecipt = new Recipe(maxIngredients);
currRecipe.Category = (FoodCategory)comboBoxCategory.SelectedIndex;
currRecipe.Name = textBoxRecipeName.Text.Trim();
currRecipe.Description = richTextBoxDescription.Text.Trim();
Console.WriteLine("Adding recipe: " + currRecipe.ToString());
bool result = recipemanager.Add(currRecipe);
Console.WriteLine("Result was " + result + " for adding to recipe list");
UpdateGUI();
// No need to reset it, use new one everytime.
//currRecipe.DefaultValues();
}

Related

Pass class object by reference to method override

I've been attempting to write a section of code for this project so that it can print out whichever BasePlayer object's hand along with the total as such (: (card) (card) (total) - (playerName)) and I've been trying to override ToString() to be able to accomplish this. Issue is I need to pass the referenced object's specific hand but can't figure out how to pass by reference while using an override. I'm not sure if it's syntax or how I'm doing it, I would just like to fix it.
The issue is the bottom most function:
using System;
using System.Collections.Generic;
using System.Text;
using Blackjack_C;
namespace Blackjack_C
{
public class BasePlayer : Hand
{
public string name;
private (ref BasePlayer ap);
public BasePlayer(ref string name)
{
this.name = name;
}
Hand hand = new Hand();
public bool IsBusted()
{
return hand.getTotal() > 21;
}
public void Bust()
{
Console.Write(name + " busts.");
}
public override string ToString(ref BasePlayer ap)
{
string output = ":\t";
if (!(ap.m_Cards.Count == 0))
{
foreach (var c in ap.m_Cards)
{
output += (c + "\t");
}
if (ap.getTotal() != 0)
{
output += ("(" + ap.getTotal() + ")");
}
return output;
}
else
{
return("<empty>");
}
}
}
}
Here is the definition of the Hand class:
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Blackjack_C;
namespace Blackjack_C
{
public class Hand
{
protected List<Card> m_Cards;
~Hand()
{
clearHand();
}
public void add(Card pCard)
{
m_Cards.Insert(m_Cards.Count, pCard);
}
public void clearHand()
{
m_Cards.Clear();
}
public int getTotal()
{
// If the hand is empty it cannot get total
if (m_Cards.Count == 0)
{
return 0;
}
// Gets total value of deck (doesn't run if Dealer's hand)
int total = 0;
foreach (var c in m_Cards)
{
total += c.getValue();
}
// Bool to check if the hand has an Ace in it (doesn't run if Dealer's hand)
bool containsAce = false;
foreach (var c in m_Cards)
{
if (c.getValue() == (int) Card.card_face.Ace)
{
containsAce = true;
}
}
// Checks if hand is dealer's hand and get's value whilst keeping it secret from the player
if (m_Cards.First().getValue() == 0)
{
//int total = 0;
foreach (var c in m_Cards)
{
total += c.getDealerValue();
}
//bool containsAce = false;
foreach (var c in m_Cards)
{
if (c.getDealerValue() == (int) Card.card_face.Ace)
{
containsAce = true;
}
}
}
// Checks if total is less than 11 to see if changing Ace to = 11 instead of = 1 is necessary
if (containsAce && total <= 11)
{
total += 10;
}
return total;
}
public Card getCard(int index)
{
if (index >= m_Cards.Count || index < 0)
return m_Cards[0];
else
{
return m_Cards[index];
}
}
}
}
Sorry for lack of a good post, this is my first time posting a question here.
i created the hand object with assumptions. Hand can have 2 or more card.
so you can try like this :
public class BasePlayer
{
public Hand Hand { get; set; }
public string Name { get; set; }
public BasePlayer(ref string name)
{
Name = name;
}
public bool IsBusted()
{
return Hand.GetTotal() > 21;
}
public void Bust()
{
Console.Write(Name + " busts.");
}
public override string ToString()
{
// you can access referenced string and specific hand on here
return string.Join(' ',Hand.Cards.Select(card=>$"{(card)}")) + $" {(Hand.GetTotal()) } "+ Name;
}
}
public class Hand
{
public List<int> Cards { get; set; }
public int GetTotal()
{
return Cards.Sum();
}
}

SortedDictionary key Object duplicate Problem

I have a SortedDictionary with Object as key, which implements the IComparable interface,
but the result is not correct.
here is the code
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Collections.Concurrent;
namespace TestApp {
public class Program
{
public class UserPrice : IComparable<UserPrice>
{
public string Wxid { get; set; }
public int Num { get; set; }
public int Price{ get; set; }
public DateTime PriceTime { get; set; }
public int CompareTo(UserPrice other)
{
if (Wxid == other.Wxid)
{
return 0;
}
if (Price != other.Price)
{
return other.Price.CompareTo(Price);
}
return PriceTime.CompareTo(other.PriceTime);
}
public override string ToString()
{
return String.Format("wxid={0}, num={1}, price={2}, priceTime={3}", Wxid, Num, Price, PriceTime);
}
}
private SortedDictionary<UserPrice, int> sortedPriceDict = new SortedDictionary<UserPrice, int>();
private BlockingCollection<UserPrice> chan = new BlockingCollection<UserPrice>();
private void MockMessage()
{
sortedPriceDict = new SortedDictionary<UserPrice, int>();
var task = Task.Run((Action)MockRecvMsg);
for (var i = 0; i < 10; i++)
{
var j = i;
Task.Run(() => MockSendMsg(j));
}
task.Wait();
}
private void MockRecvMsg()
{
while (true)
{
var p = chan.Take();
sortedPriceDict[p] = 1;
//Console.WriteLine(sortedPriceDict.Count + "," + p);
if(sortedPriceDict.Count > 10)
{
break;
}
}
foreach(var up in sortedPriceDict){
Console.WriteLine(up);
}
}
private async void MockSendMsg(int i)
{
var wxId = String.Format("user_{0}", i);
var rand = new Random();
var basePrice = 320;
while(true)
{
var up = new UserPrice();
up.Wxid = wxId;
up.Price = rand.Next(basePrice, basePrice + 100) * 100;
up.Num = rand.Next(1, 10);
up.PriceTime = DateTime.Now;
//Console.WriteLine(up);
chan.Add(up);
await Task.Delay(rand.Next(1, 5) * 1000);
}
}
public static void Main()
{
var main = new Program();
main.MockMessage();
}
}
}
I want to sort by [Price desc, PriceTime asc], user price with the same Wxid should by unique in the SortedDictionary, I start 10 Tasks to produce messages from 10 users, and 1 consumer to save the messages into the sortedDictionary, but after run for a while, the program will stop, because the dictionary's count is > 10, so what's wrong with my code ? Do I miss anything?

trying to popup DisplayAlert when game finish in xamarin

I am building a game in xamarin in which I am trying to show a DisplayAlert Popup when the game is finished (after 8 seconds). However as the time gets to zero it wont show.
If i put the DisplayAlert at the beginning of the time it works fine.
Can you please explain, why this is the case?
The DisplayAlert line is located in the "OnTimedEvent" Method at the end of the code in this ViewModel:
using System;
using System.Diagnostics;
using System.Timers;
using CBTGAME1.Models;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace CBTGAME1.ViewModels
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class GamePageViewModel : ObservableObject
{
Animals aninames = new Animals();
Timer timer;
private int countSecond;
public int CountSecond
{
get { return countSecond; }
set
{
countSecond = value;
OnPropertyChanged(nameof(CountSecond));
}
}
private string nowanimal = null;
public string Nowanimal
{
get { return nowanimal; }
set {
nowanimal = value;
OnPropertyChanged(nameof(Nowanimal));
}
}
public Command Generate { get; }
public Command button1 { get; }
public Command button2 { get; }
public Command button3 { get; }
private int yourscore = 0;
public int Yourscore
{
get { return yourscore; }
set { yourscore = value;
OnPropertyChanged(nameof(Yourscore));
}
}
private string firstb;
private string secondb;
private string thirdb;
public string Firstb
{
get { return firstb; }
set
{
firstb = value;
OnPropertyChanged(nameof(Firstb));
}
}
public string Secondb
{
get { return secondb; }
set
{
secondb = value;
OnPropertyChanged(nameof(Secondb));
}
}
public string Thirdb
{
get { return thirdb; }
set
{
thirdb = value;
OnPropertyChanged(nameof(Thirdb));
}
}
public GamePageViewModel()
{
RndAll();
timer = new Timer();
settimer();
button1 = new Command(() =>
{BtnOperation(firstb); });
button2 = new Command(() =>
{BtnOperation(secondb); });
button3 = new Command(() =>
{BtnOperation(thirdb); });
}
public void BtnOperation(string btname)
{
if (btname == Nowanimal)
Yourscore = Yourscore + 1;
else Yourscore = Yourscore - 1;
RndAll();
}
public void RndAll()
{
Random rnd = new Random();
Nowanimal = aninames.Animalss[rnd.Next(0, 3)];
int i = rnd.Next(0, 3);
Firstb = aninames.Animalss[i];
if (i == 2) i = 0;
else i++;
Secondb = aninames.Animalss[i];
if (i == 2) i = 0;
else i++;
Thirdb = aninames.Animalss[i];
}
public void settimer()
{
CountSecond = 8;
timer.Interval = 1000;
timer.Elapsed += OnTimedEvent;
timer.Enabled = true;
}
private void OnTimedEvent(object sender, ElapsedEventArgs e)
{
CountSecond--;
if (CountSecond == 0)
{
timer.Stop();
App.Current.MainPage.DisplayAlert("finished", "have a good day", "Exit");
}
}
}
}
1) DisplayAlert returns a Task, so await it
2) Call it on the main/ui thread
Device.BeginInvokeOnMainThread (async() => {
await App.Current.MainPage.DisplayAlert("finished", "have a good day", "Exit");
});

My property only has a get, but I want that value to change everytime I call it

I am struggling with the this for a few hours now. I only want to use a get in my property. When I call a function, it gets a number from that property(10) and should substract 1 from the 10, which makes 9. But I have no idea how to save this 9, and do it minus 1 everytime, so the next time I call it, it becomes 8. I Hope this is clear enough.
main.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
do
{
Zwakmonster zwakmonster = new Zwakmonster();
Sterkmonster sterkmonster = new Sterkmonster();
List<IMonster> monster = new List<IMonster>();
string lijn;
string test = "exit";
string nieuwelijn;
string zwak = "zwakmonster";
string sterk = "sterkmonster";
string groen = "groen";
string geel = "geel";
Sterkmonster henk = new Sterkmonster();
henk.Naam = sterk;
henk.Kleur = groen;
Zwakmonster piet = new Zwakmonster();
piet.Kleur = geel;
piet.Naam = zwak;
Console.WriteLine("Schrijf zwakmonster_iemand of sterkmonster_iemand");
lijn = Console.ReadLine();
if (lijn == test)
{
Environment.Exit(0);
}
else if (lijn.StartsWith("hit"))
{
if (lijn.StartsWith("hit "))
{
nieuwelijn = lijn.Remove(0, 4);
if (nieuwelijn == sterk)
{
henk.Hit();
Console.WriteLine(sterkmonster);
}
else if (nieuwelijn == zwak)
{
piet.Hit();
Console.WriteLine(zwakmonster);
}
else
{
Console.WriteLine("iets ging er fout");
}
}
else
{
Console.WriteLine("Ben je misschien een spatie vergeten na ''hit''?\n");
}
}
else
{
Console.WriteLine("Verkeerd commando ingevoerd\n");
}
} while (1 == 1);
}
}
}
IMonster.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
interface IMonster
{
string Naam
{
get;
set;
}
string Kleur
{
get;
set;
}
int Levens
{
get;
}
void Hit();
}
}
zwakmonster.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Zwakmonster : IMonster
{
private string mijnNaam;
private string mijnKleur;
private int mijnLevens = 10;
private int nieuwelevens;
public string Naam
{
get { return mijnNaam; }
set { mijnNaam = value; }
}
public string Kleur
{
get { return mijnKleur; }
set { mijnKleur = value; }
}
public int Levens
{
get { return mijnLevens; }
}
public void Hit()
{
mijnLevens = mijnLevens - 1;
nieuwelevens = mijnLevens;
Console.WriteLine(nieuwelevens);
}
}
}
Change this
public void Hit()
{
newlife = mijnLevens - 1;
}
to this
public void Hit()
{
mijnLevens = mijnLevens - 1;
newlife = mijnLevens;
}
this will make sure mijnLevens is decremented. Currently, mijnLevens is always 10.
Change this:
do
{
Zwakmonster zwakmonster = new Zwakmonster();
To this
Zwakmonster zwakmonster = new Zwakmonster();
do
{
So that you don't create a new object for every iteration.
Allan Elder already gave the right answer, to make things less complicated i would use only one var for your lives count
class Zwakmonster : IMonster
{
private string mijnNaam;
private string mijnKleur;
private int lives = 10;
public string Naam
{
get { return mijnNaam; }
set { mijnNaam = value; }
}
public string Kleur
{
get { return mijnKleur; }
set { mijnKleur = value; }
}
public int Levens
{
get { return lives; }
}
public void Hit()
{
lives = lives - 1;
}
}
mijnLevens will always have the value 10.
You need to assign the reduced value back to mijnLevens

Linked List: Insert item btween current and current.next

Currently I am learning how to build my own linked list in C#. I have created a function called AddTrees that adds a tree to the end of the list. User create their trees through textboxes input:tree_name, tree_height, tree_price and tree_instock. I am requesting help with my InsertTree which is not inserting a tree between current and current.next_tree? But instead of instead of inserting it between, it adds it to the top of the list.
namespace Tree_farm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public class TheTrees
{
private string tree_type = " ";
private int tree_height = 0;
public double tree_price = 0;
private int tree_instock = 0;
public TheTrees next_tree;
public TheTrees(string newtree, int newheight, int newinstock, double newprice)
{
tree_type = newtree;
tree_height = newheight;
tree_price = newprice;
tree_instock = newinstock;
next_tree = null;
}
public override string ToString()
{
return tree_type + " " + tree_height + " " + tree_price + " " + tree_instock;
}
}
public class ListForTrees
{
public TheTrees first_tree;
public TheTrees last_tree;
public int count = 0;
public ListForTrees(TheTrees new_tree)
{
first_tree = new_tree;
last_tree = new_tree;
count = 1;
}
public ListForTrees()
{
}
public void InsertTree(TheTrees new_tree)
{
TheTrees current = first_tree;
if (count == 0)
{
first_tree = new_tree;
last_tree = new_tree;
count = 1;
}
else if (count != 0)
{
if (new_tree.tree_price <= first_tree.tree_price)
{
new_tree.next_tree = first_tree;
first_tree = new_tree;
}
else if (new_tree.tree_price >= last_tree.tree_price)
{
last_tree.next_tree = new_tree;
last_tree = new_tree;
}
else
{
while (new_tree.tree_price > current.next_tree.tree_price)
{
current.next_tree = current;
}
new_tree.next_tree = current.next_tree;
current.next_tree = new_tree;
}
count++;
}
}
public void AddTree(TheTrees new_tree)
{
TheTrees current = first_tree;
if (count == 0)
{
first_tree = new_tree;
last_tree = new_tree;
count = 1;
}
else if (count != 0)
{
if (new_tree.tree_price <= first_tree.tree_price)
{
new_tree.next_tree = first_tree;
first_tree = new_tree;
}
else if (new_tree.tree_price >= last_tree.tree_price)
{
last_tree.next_tree = new_tree;
last_tree = new_tree;
}
else
{
while (new_tree.tree_price > current.next_tree.tree_price)
{
current = current.next_tree;
}
new_tree.next_tree = current.next_tree;
current.next_tree = new_tree;
}
count++;
}
}
public void ClearTrees()
{
first_tree = null;
count = 0;
}
}
ListForTrees mainlist = new ListForTrees();
private void Form1_Load(object sender, EventArgs e)
{
}
private void BtnInsertTree_Click(object sender, EventArgs e)
{
//Insert Code
try
{
int height = Convert.ToInt32(TxtTreeHeight.Text);
int stock = Convert.ToInt32(TxtTreeStock.Text);
double price = Convert.ToDouble(TxtTreePrice.Text);
TheTrees treeinsert = new TheTrees(TxtTreeName.Text, height, stock, price);
mainlist.InsertTree(treeinsert);
}
catch
{
MessageBox.Show("Please check intput fields");
}
}
private void BtnAddTree_Click(object sender, EventArgs e)
{
try
{
int height = Convert.ToInt32(TxtTreeHeight.Text);
int stock = Convert.ToInt32(TxtTreeStock.Text);
double price = Convert.ToDouble(TxtTreePrice.Text);
TheTrees treeadd = new TheTrees(TxtTreeName.Text, height, stock, price);
mainlist.AddTree(treeadd);
}
catch
{
MessageBox.Show("Please check intput fields");
}
}
}
}
First, I think your expected result is wrong. It appears you want the linked list sorted in order of price (lowest to highest). If so, Cypress should actually go at the end of your list, not in the middle (80.00 > 50.00 > 2.00).
Secondly, I believe the issue rests in your while loop.
while (new_tree.tree_price > current.next_tree.tree_price)
{
current.next_tree = current;
}
I believe what you're trying to do is walk down your linked list. What you're actually doing is mucking up your linked list by changing current.next_tree to point to itself. Changing it to the following is a positive first step towards correcting your algorithm:
while (new_tree.tree_price > current.next_tree.tree_price)
{
current = current.next_tree;
}
EDIT: It should be noted that I do not get the same error that you get in your original post. When I insert items in the same order that you claim to, I get the list in correct sorted order. This is due to the fact that Cypress goes to the end, as expected. How did you get the result that you claim in the question?

Categories

Resources