简体   繁体   English

链表的trim()方法

[英]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: 但是,在Java中制作一个String trim()方法(除去前导/尾随空白),我知道这的基本代码是:

    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. 更具体地说,是使用Node类的链表。

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 “使用Node类的链接列表”下,您的意思是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. 您应该记住,在Java中未公开LinkedList的内部实现(请注意: java.util.LinkedList.Node具有私有访问修饰符),所有修改都是通过迭代器和LinkedList本身的方法执行的。

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: 但是,如果您要通过练习通过链表重新实现可变字符串 (如果不是作为练习,那么就在此处停止并使用StringBuilderStringBuffer ),那么,假设您使用双链表实现它,它将像这样:

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 head引用设置为最后一个提取的元素,将last提取元素的prev引用设置为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 将尾引用设置为最后一个获取的元素,将最后提取的元素的下一个引用设置为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): UPDATE使用您提供的代码尝试执行以下操作(由于您使用的是单链接列表,因此与上述列表略有不同):

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,为什么不仅仅遍历每个项目呢?

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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