简体   繁体   中英

trim() method for linked list

I have a question, I've looked around on the internet but couldn't find an example. But making a String trim() method in java (remove lead/trailing whitespace), I know the basic code for this is:

    public LString trim(){
    int i = this.size;
    int j = 0;
    int k = this.offset;
    char[] arrayOfChar = this.data;
    while ((j < i) && (arrayOfChar[(k + j)] <= ' '))
      ++j;
    while ((j < i) && (arrayOfChar[(k + i - 1)] <= ' '))
      --i;
    return (((j > 0) || (i < this.size)) ? substring(j, i) : this);
}

But, how would you write this same method, but applied to a linked list? More specifically, a linked list that uses a Node class.

Here is what I did....correct me if this is wrong...I'll include relevant class information that pertains to the question.

public class LString{

   private Node front = null;  //first val in list
   private Node back;   //last val in list
   private int size = 0;
   private int i;
   private int offset;

   public LString(){
      //construct empty list
      Node LString = new Node();
      front = null;

   }
.......//skip down some methods to this one

   //returns new lstring that is slice of lstring
   //contains an endIndex as well
   public LString substring(int beginIndex, int endIndex){
      Node current = this.front;
      int size = 0;
      while(current != null && size < beginIndex){
         size++;
         current = current.getNext();
      }
      front = new Node();
      front.setData(current.getData());
      Node ocurrent = front;

      while(current != null && size < endIndex){
         current = current.getNext();
         Node curr2 = new Node();
         curr2.setData(current.getData());

         ocurrent.setNext(curr2);
         ocurrent = curr2;
         size++;
      }    
      ocurrent.setNext(null);    //set next val to null to term string
      return this;
   }

   public LString trim(){
      String lstr;
      int i = this.size;
      int m = this.offset;
      int k = charAt(m);
      Node current = front;
      while(current != null){
         current = current.getNext();
         if(current.data > '\u0020'){
         return this;
         } else if(current.data < '\u0020'){
            LString lstring = new LString();    //this worked!?
            return lstring;
           }
      }
      return this.substring(k, m+1);
   }  

...............................................................

//My Node class:


public class Node{
   public char data;
   public Node next;

   //constructors from page 956
   public Node()
   {
      this('\0',null);  //'\0' is null char for java
   }

   public Node(char initialData, Node initialNext)
   {
      data = initialData;
      next = initialNext;
   }
   }

(If you are unfamiliar with the node class, it basically just creates a singly linked node to use as your links between data in your linked list class)

I've never seen an example or anything, so I thought I'd ask the community.

Assuming that

  • by trimming the list you want to remove leading and trailing elements that are null
  • and under "linked list that uses a Node class" you mean java.util.LinkedList

You should keep in mind that in java internal implementation of LinkedList is not exposed (note: java.util.LinkedList.Node has private access modifier), all modifications are performed through methods of iterator and LinkedList itself.

Implementation would be:

public static void trim (LinkedList list){
    if (list == null || list.size() == 0) return;

    Object element = null;

    ListIterator i = list.listIterator();
    while (i.hasNext() && element == null) {
        element = i.next();
        if (element == null) {
            i.remove();
        }
    }

    element = null;
    i = list.listIterator(list.size());
    while (i.hasPrevious() && element == null) {
        element = i.previous();
        if (element == null) {
            i.remove();
        }
    }
}

However if you are reimplementing mutable strings via linked list as an exercise (if not as an exercise then stop right there and use StringBuilder or StringBuffer ), then, assuming that you implement it with doubly linked list, it will go like this:

EDIT: my bad, you can iterate to the first non-empty element and set reference directly to it, updated algorithm

  1. Fetch first element
  2. While fetched element is empty fetch next
  3. Set head reference to the last fetched element, set last fetched element's prev reference to null
  4. Fetch last element
  5. While fetched element is empty fetch previous
  6. Set tail reference to the last fetched element, set last fetched element's next reference to null

UPDATE With code you provided try something like this (since you are using singly-linked list, it is slightly different then the one described above):

public void trim(){
    //early out if empty
    if (front == null || back==null) return;

    Node current = front;

    //looking for the first non-empty element
    while(current != null && current.data<'\u0020' ){
        current = current.next;
    }

    //left trim
    this.front = current;

    //looking for last non-empty element
    while (current!=null&&current.next!=null&&current.next.data>'\u0020'){
        current = current.next;
    }

    //right trim
    this.back = current;
    if (current!=null){
        current.next = null;
    }
}

Assuming you just want to trim each String in a LinkedList, why not just iterate over each item?

LinkedList<String> myNodes = new LinkedList<String>();
myNodes.add('This is a node ');
myNodes.add(' another node    '));

for (String s : myNodes){
  s.trim();
}

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