How do you get the index of a number in a linked list?

后端 未结 5 356
天命终不由人
天命终不由人 2021-01-14 01:50

I have a linked list constructed as follows:

LinkedList linked = new LinkedList();
var array = new int[] { 23, 55, 64, 65 };
foreach (         


        
5条回答
  •  执笔经年
    2021-01-14 02:40

    You can make one up. :) I found this question trying to figure out how to qsort a linked list. And it hit me since I'm sorting structs anyway all I have to do is give each one a unique identifier. Which will probably be the sequence in which they're created. Just add an int field called seq or idx to each node. Change your ints to structs with the ints inside and attach another int field that's your improvised index. Traversing the list will be cumbersome. But you bind the original ints to indexes.

    If you don't expect the data to move around you could build an array of pointers to elements of your linked list. Start at the beginning, use the pointer to next, keep doing that and count how many hops. Then allocate your array, start at the beginning of the list again and record in your array the addresses of the next pointers. But someone or something (another thread?) could screw it up by moving or adding or removing an element. The list would continue to work but the array would need to be scrapped and redone. Could be relatively fast, but how to detect the change reliably?

    Circular? Just use modulo so to move forward idx = (idx + 1) % N where N is the total count of fields. For normal C anyway, I don't know what C#'s limitations are.

提交回复
热议问题