简体   繁体   中英

How can I find if a number in a doubly linked list is between max and min?

I want to create a method called inBetween that accepts an item as a parameter and returns true if the item is “in between” the smallest and largest list elements. That is, based on the compareTo method defined for list elements, the item is larger than the smallest list element and smaller than the largest list element. Otherwise, the method returns false (even if the item “matches” the smallest or largest element).

public class DoublyLinkedList {

private Link first;               // ref to first item
private Link last;                // ref to last item
// -------------------------------------------------------------

public DoublyLinkedList() // constructor
{
    first = null;                  // no items on list yet
    last = null;
}
// -------------------------------------------------------------

public boolean isEmpty() // true if no links
{
    return first == null;
}
// -------------------------------------------------------------

public void insertFirst(long dd) // insert at front of list
{
    Link newLink = new Link(dd);   // make new link

    if (isEmpty()) // if empty list,
    {
        last = newLink;             // newLink <-- last
    } else {
        first.previous = newLink;   // newLink <-- old first
    }
    newLink.next = first;          // newLink --> old first
    first = newLink;               // first --> newLink
}
// -------------------------------------------------------------

public void insertLast(long dd) // insert at end of list
{
    Link newLink = new Link(dd);   // make new link
    if (isEmpty()) // if empty list,
    {
        first = newLink;            // first --> newLink
    } else {
        last.next = newLink;        // old last --> newLink
        newLink.previous = last;    // old last <-- newLink
    }
    last = newLink;                // newLink <-- last
}
// -------------------------------------------------------------

public Link deleteFirst() // delete first link
{                              // (assumes non-empty list)
    Link temp = first;
    if (first.next == null) // if only one item
    {
        last = null;                // null <-- last
    } else {
        first.next.previous = null; // null <-- old next
    }
    first = first.next;            // first --> old next
    return temp;
}
// -------------------------------------------------------------

public Link deleteLast() // delete last link
{                              // (assumes non-empty list)
    Link temp = last;
    if (first.next == null) // if only one item
    {
        first = null;               // first --> null
    } else {
        last.previous.next = null;  // old previous --> null
    }
    last = last.previous;          // old previous <-- last
    return temp;
}
// -------------------------------------------------------------
// insert dd just after key

public boolean insertAfter(long key, long dd) {                              
// (assumes non-empty list)
    Link current = first;          // start at beginning
    while (current.dData != key) // until match is found,
    {
        current = current.next;     // move to next link
        if (current == null) {
            return false;            // didn't find it
        }
    }
    Link newLink = new Link(dd);   // make new link

    if (current == last) // if last link,
    {
        newLink.next = null;        // newLink --> null
        last = newLink;             // newLink <-- last
    } else // not last link,
    {
        newLink.next = current.next; // newLink --> old next
        // newLink <-- old next
        current.next.previous = newLink;
    }
    newLink.previous = current;    // old current <-- newLink
    current.next = newLink;        // old current --> newLink
    return true;                   // found it, did insertion
}
// -------------------------------------------------------------

public Link deleteKey(long key) // delete item w/ given key
{                              // (assumes non-empty list)
    Link current = first;          // start at beginning
    while (current.dData != key) // until match is found,
    {
        current = current.next;     // move to next link
        if (current == null) {
            return null;             // didn't find it
        }
    }
    if (current == first) // found it; first item?
    {
        first = current.next;       // first --> old next
    } else // not first
    // old previous --> old next
    {
        current.previous.next = current.next;
    }

    if (current == last) // last item?
    {
        last = current.previous;    // old previous <-- last
    } else // not last
    // old previous <-- old next
    {
        current.next.previous = current.previous;
    }
    return current;                // return value
}
// -------------------------------------------------------------

public void displayForward() {
    System.out.print("List (first-->last): ");
    Link current = first;          // start at beginning
    while (current != null) // until end of list,
    {
        current.displayLink();      // display data
        current = current.next;     // move to next link
    }
    System.out.println("");
}
// -------------------------------------------------------------

public void displayBackward() {
    System.out.print("List (last-->first): ");
    Link current = last;           // start at end
    while (current != null) // until start of list,
    {
        current.displayLink();      // display data
        current = current.previous; // move to previous link
    }
    System.out.println("");
}
// -------------------------------------------------------------

public DoublyLinkedList inBetween(long n) {

}
}  // end class DoublyLinkedList
////////////////////////////////////

public class InBetweenDemo
{
public static void main(String[] args)
  {                             // make a new list
  DoublyLinkedList theList = new DoublyLinkedList();

  theList.insertFirst(22);      // insert at front
  theList.insertFirst(44);
  theList.insertFirst(66);

  theList.insertLast(11);       // insert at rear
  theList.insertLast(33);
  theList.insertLast(55);

  theList.displayForward(); 
  int n=55;// display list forward
  System.out.println("inBetween("+n+") "+ inBetween(n));
  theList.displayBackward();    // display list backward

  theList.deleteFirst();        // delete first item
  n=55;
  System.out.println("inBetween("+n+") "+ theList.inBetween(n));

  theList.deleteLast(); 
  n=33;
  System.out.println("inBetween("+n+") "+ theList.inBetween(n));
  theList.deleteKey(22);        // delete item with key 11
  System.out.println("inBetween("+n+") "+ theList.inBetween(n));

  theList.displayForward();     // display list forward

  theList.insertAfter(11, 77);  // insert 77 after 22
  theList.insertAfter(33, 88);  // insert 88 after 33

  theList.displayForward();     // display list forward
  }  // end main()
}  // end class DoublyLinkedApp
////////////////////////////////////////////////////////////////

I was thinking that I could assign a max and min and then check if the parameter is less than and greater than each respective values. If it was then I would return true, if not return false. I'm not sure how I would start the code of looking for the max and min in an unordered list.

There are two possible ways to solve your problem. (There might be other methods)

  1. You can make another method that will go through your linked list and find min and max . And just call this method in your inBetween method. This method will have the worst case of O(n). (If you are planning to do this then having a variable for min and max is not enough, you have to call the method every time you call inBetween since there is a possibility that the values have been updated)
  2. Have a variable for min and max then update it after every insert and delete. It must be of type Link . In insert it will just have the runtime of O(1) since you will just compare their values directly. While in delete you will have to compare the key, if it has the same key then you have to find another min or max . Thus you should also create a method to find min and max . And in your inBetween method you will just have to get the variables min and max . There is no possibility that the values for min and max will update while executing inBetween since you are updating min and max every insert and delete.

So there you go, just choose what you will implement from the two.

Just iterate the list and make sure your item is less than at least one element and more than another:

public boolean inBetween(long n) {
    boolean less = false, more = false;
    for (Link current = first; current != null; current = current.next)
        if ((less |= n < current.dData) & (more |= n > current.dData))
            return true;
    return false;
}

I think you should create two variables, MAX and MIN firstly. After, run over the List and find the MAX and the MIN values. So, pick the value you want to campare and make the comparison. If the value is bigger than MIN and smaller than MAX, it is a valid number. I sugest you add a variable called listLenght on the class of the List. When you add something, update the variable listLenght. When you remove, do the same.

Iterate over the list to find the min and max values, then return true if the input value is greater than min and less than max :

public static boolean isBetween(List<Integer> list, int value){

    int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;

    for (int i : list){

        if (i < min)
            min = i;

        if (i > max)
            max = i;
    }

    return value > min && value < max;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM