Code to locate a specific item in a linked list and remove it - linked-list

For my Computer Science course we are needing to create 2 functions. One function needs to locate the serial position of the item being searched for (an int in this case) and the index of the previous item. The locateNode function (the function described above) needs to be used within the Remove function as well as other functions already written by the professor in the class. Remove is simply supposed to take the item before the one being removed and make it point to the item that was being pointed to by the removed item. Finally it will take the removed node and push it into an avail list within the same array (essentially there are 2 linked lists in the one array.) My functions are giving me the wrong output and I currently do not know which is wrong or if both functions are wrong.
void SortedList::Remove(ItemType anItem, bool& success)
// IN OUT
{
int previous, position;
success=locateNode(anItem, previous, position);
cerr<<success<<endl;
if (success)
{
int current=list[0].next;
list[previous].next=list[list[previous].next].next;
for (int i=1; i<position; i++)
{
current=list[i].next;
}
PushAvail(current);
}
} // end Remove
bool SortedList::locateNode(
ItemType anItem, int& previous, int& position) const
{
position=1;
previous=0;
int current=list[0].next;
bool isPresent = false;
for (int count=1; count <= size; count++)
{
if (list[current].item >= anItem)
{
if ( list[current].item == anItem)
{
cerr<<"Position "<< position<< endl;
cerr<<"Previous "<< previous<< endl;
isPresent = true;
}
return isPresent;
}
position++;
previous=list[previous].next;
current=list[current].next;
}
return isPresent;
}

Related

I'm getting into infinite while loop (linked lists c)

I'm stuck in a while loop (the one that prints "no" ):
#include<stdlib.h>
#include<stdio.h>
typedef struct bill {
int value;
struct bill *next;
} list;
void printlist(list *head) {
list *temp = head;
while (temp != NULL)
printf("%d ",temp->value), temp = temp->next;
}
void insert_at_end(list *head, int value) {
list *current, *first;
first = malloc(sizeof(list));
if (head == NULL)
head = first;
else {
current = head;
while (current->next != NULL) {
current = current->next;
printf("no");
}
}
}
void main() {
list *head = NULL;
head = malloc(sizeof(list));
for (int i = 0; i < 10; i++)
insert_at_end(head, i);
printlist(head);
}
I'm not sure why, but current never gets to NULL. I watched numerous videos and they all do the same:
while (current != NULL)
current = current->next
...which should just get to NULL at one point, but it doesn't in my case.
There are these issues:
When you do head = malloc(sizeof(list)), the members of that node are still undefined, including its next member. As a consequence, when you get into the else block in the insert_at_end function, the loop will access this undefined next pointer and bring about undefined behaviour.
Similar to the previous problem, also first does not get initialised with a value and a next member.
In the else block in the insert_at_end function there is no code that attaches the new node to the list.
In the if block in the insert_at_end function, the value of head is altered. But this just changes the value of a local variable -- the caller will not see this change. For that to happen you should alter the function parameter so that it is a pointer to the head pointer.
The creation of a head node in the main program seems unwaranted -- you should start with an empty list, i.e. with head equal to NULL.
void main is not correct. It should be int main, and the appropriate value should be returned by it.
Here is the correction to the two functions that have issues:
// This function accepts a pointer to a head-pointer, so the head-pointer
// can be changed and the caller will receive that change.
void insert_at_end(list **head, int value){
list *current, *first;
first = malloc(sizeof(list));
first->value = value; // This was missing
first->next = NULL; // This was missing
if (*head == NULL) {
*head = first;
} else {
current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = first; // This was missing
}
}
// The main method has an int return type
int main() {
list *head = NULL;
// Do not create a node here.
for (int i = 0; i < 10; i++) {
insert_at_end(&head, i); // pass pointer to head-pointer
}
printlist(head);
return 0;
}

InputFilter not behaving correctly

I have the following input filter on my Xamarin.Android app. When created, it sets if the input is caps only, alpha only, numeric only, alpha with separators etc - it's fairly flexible. The code is a direct port of some Java code found on here.
public ICharSequence FilterFormatted(ICharSequence source, int start, int end, ISpanned dest, int dstart, int dend)
{
if (source is SpannableStringBuilder)
{
var sourceAsSpannableBuilder = (SpannableStringBuilder)source;
for (var i = end - 1; i >= start; i--)
{
if (!isCharacterOk(source.CharAt(i)))
{
sourceAsSpannableBuilder.Delete(i, i + 1);
}
}
return source;
}
else
{
var filteredStringBuilder = new SpannableStringBuilder();
for (int i = start; i < end; i++)
{
var currentChar = source.CharAt(i);
if (isCharacterOk(currentChar))
{
filteredStringBuilder.Append(currentChar);
}
}
return filteredStringBuilder;
}
}
The isCharacterOK method checks if the character is correct or not (for example the filter for caps only checks if the character is Upper and if Alpha is set). It works happily.
The filter works fine for code going forward (for example, if I type ASDFGjhkl, only ASDFG show in the edittext).
The problem is when I press delete, the dest seems to still include hjkl which means I need to hit delete 5 times before the letter G is removed.
Have I stumbled on a Xamarin bug, an android oddity or is this correct behavior? It seems very strange that dest is somehow picking up characters not in the EditText widget.
you could change like this:
if (source is SpannableStringBuilder)
{
var sourceAsSpannableBuilder = (SpannableStringBuilder)source;
for (var i = end - 1; i >= start; i--)
{
if (!isCharacterOk(source.CharAt(i)))
{
sourceAsSpannableBuilder.Delete(i, i + 1);
//return the new SpannableStringBuilder.
sourceAsSpannableBuilder = new SpannableStringBuilder(sourceAsSpannableBuilder);
}
}
return sourceAsSpannableBuilder;
}
the effect like below:

How to know the new ticket number after partial closed a position

When we OrderClose a position partially (say you buy at 2 lots but only close for 1 Lot), it will open a new ticket number, but how do we know that ticket number specifically?
Need to loop over all tickets, your new ticket has same magic number and comment, as well as all other entry parameters. Since new ticket is open, its ticket number is larger then the closed one. As a result, the idea is to filter all open orders by symbol and magic, then find the largest ticket with same entry time as the just closed one.
Script
int cou;
///////////////////////////////////////////
void OnStart()
{
ticket_search_start_f();
}
///////////////////////////////////////////
void ticket_search_start_f()
{
int tick_start;
int tick_curr;
int str_start;
for (int i=OrdersTotal()-1; i>=0; i--)
{
if(!OrderSelect(i,SELECT_BY_POS,MODE_TRADES)) continue;
str_start=StringFind(OrderComment(),"from #");
if(str_start!=-1)
{
tick_curr=OrderTicket();
tick_start=ticke_search_f(int(StringSubstr(OrderComment(),str_start+6)));
Alert("Ticket:"+string(tick_curr)," Start ticket:"+string(tick_start)," Parts:",cou);
}
}
}
////////////////////////////////////////////////////////////////////////
int ticke_search_f(int ticke)
{
//no order
if(!OrderSelect(ticke,SELECT_BY_TICKET)) return(-1);
//parts
int tick=ticke;
int tick_fin=ticke;
cou=1;
while(tick!=-1)
{
tick=comme_search_f(tick);
if(tick!=-1)
{
tick_fin=tick;
cou++;
}
}
//return ticket of first closed part
return(tick_fin);
}
////////////////////////////////////////////////////////
int comme_search_f(int tick_s)
{
int tick=-1;
for (int i=OrdersHistoryTotal()-1; i>=0; i--)
{
if(!OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)) continue;
if(StringFind(OrderComment(),string(tick_s))!=-1 && StringFind(OrderComment(),"from")==-1)
{
tick=OrderTicket();
break;
}
}
return(tick);
}

Method declaration in java

I have a question regarding this code, you can see in some methods that there are comments with a return, that is because I think I have to use a return method instead of a void method. My teacher told me to transform them to a void class, but isn't a method which modifies field variables suposed to return something? I'm in doubt because sometimes my teacher seems to not know so much about programming or has some doubts so, thank for your help beforehand.
public class ArraysClass {
private int[] array;
private int arrayLength;
public ArraysClass() {
setArrayLength();
array = new int[arrayLength];
}
public int setArrayLength() {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number to set the length of the array:");
arrayLength = scanner.nextInt();
System.out.println();
return arrayLength;
}
public void fillArray() {
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < arrayLength; i++) {
System.out.println("Type a number to fill position " + i);
array[i] = scanner.nextInt();
}
// return array;
System.out.println();
}
public void findNumber() {
Scanner scanner = new Scanner(System.in);
int tofind, position;
System.out.println("Enter a number to search it in the array:");
tofind = scanner.nextInt();
position = Arrays.binarySearch(array, tofind);
if (position < 0) {
System.out.println("We did not find your number.");
} else {
System.out.println("The number you typed is in the next position: " + position);
}
System.out.println();
}
public void fillMethod() {
Scanner scanner = new Scanner(System.in);
int tofill;
System.out.println("Enter a number to fill the entire array with:");
tofill = scanner.nextInt();
Arrays.fill(array, tofill);
System.out.println();
//return array;
}
public void Sortmethod() {
Arrays.sort(array);
//return array;
}
private void showArray() {
System.out.println("Showing the array...");
for (int i = 0; i < arrayLength; i++) {
System.out.println(array[i]);
}
System.out.println();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArraysClass arrayobj = new ArraysClass();
int choose;
do {
do {
System.out.println("1-Fill the array");
System.out.println("2-Find a number in the array");
System.out.println("3-Fill the entire array with a number");
System.out.println("4-Sort the array");
System.out.println("5-Show the array");
System.out.println("6-Exit");
System.out.println("Which one do you want to use?:");
choose = scanner.nextInt();
} while (choose < 1 && choose > 6);
switch (choose) {
case 1:
arrayobj.fillArray();
break;
case 2:
arrayobj.findNumber();
break;
case 3:
arrayobj.fillMethod();
break;
case 4:
arrayobj.Sortmethod();
break;
case 5:
arrayobj.showArray();
break;
case 6:
break;
}
} while (choose != 6);
}
}
In general, a method should return something if you need value from it. It is an approach used by some programmers to return a boolean even for do-only methods for success or failure or an int, for a status code. I do not follow these approaches. When I implement a method, I always ask myself how would I like to use that method. If I need a value from it, then it will have its type. Otherwise, it will be void. Let us see your methods:
setArrayLength: In general, from this name I would expect that you pass an int to it, representing the length and the method to be void. This is very common for setters, but here you are reading the actual value inside the method which is clearly inferior compared to having an int parameter, as your method will be useless if one wants to set the array length using a value not read from the console.
fillArray: I would expect this to be void, so I agree with its declaration, but again, the reading part should not be here.
findNumber: Should get the number to be found as a parameter and return an int, which represents its index, -1 if not found.
fillMethod: Should be void and should have an int parameter, which represents the value to be used to fill the array.
sortMethod: ok, maybe return the resulting array, but depends on your needs.
showArray: I would expect a PrintStream there, you will not necessarily output to System.out
General mistake: You mix methods with in/out operations to the console, the code is not general enough this way.

String Pattern matching in Blackberry

How i can do a simple pattern matching in blackberry OS 6.0. The purpose is to check whether the user name entered to the UserName edit field contains special characters.... plz help me
thanks jibysthomas
A better solution would be to control the user input by adding an appropriate TextFilter to your edit field. That has the added benefit of modifying the on-screen keyboard to match your filter on those devices so equipped.
Here is an example combining the action of two built in text filters to make one that only allows upper letters and numbers:
import net.rim.device.api.ui.text.TextFilter;
import net.rim.device.api.system.Characters;
/**
* A TextFilter class to filter for station identifiers
*/
private static class StationFilter extends TextFilter {
// Order of the supporting filters is important, NUMERIC will convert
// letters to numbers if it gets them first.
private static TextFilter[] _tf = {
TextFilter.get(TextFilter.NUMERIC),
TextFilter.get(TextFilter.UPPERCASE)
};
// Convert using the first supporting filter that has a conversion
public char convert( char character, int status) {
char c = 0;
for (int i = _tf.length - 1; i >= 0; i--) {
c = _tf[i].convert(character, status);
if (c != 0) {
return c;
}
}
return 0;
}
// Validate a space for separator, then by supporting filter
public boolean validate(char character) {
if (character == Characters.SPACE) {
return true;
}
for (int i = _tf.length - 1; i >= 0; i--) {
boolean b = _tf[i].validate(character);
if (b) {
return true;
}
}
return false;
}
}

Resources