首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >链表数据结构的java实现

链表数据结构的java实现
EN

Stack Overflow用户
提问于 2010-01-10 02:34:41
回答 5查看 5.7K关注 0票数 0

我正在尝试使用java实现链表数据结构,它可以很好地插入或删除第一个元素,但无法通过使用removeLast()方法删除最后一个元素。

我的链表节点类: LLNode类{ String value;LLNode next;

代码语言:javascript
复制
    public LLNode(String value){
        this.value = value;
        this.next = null;
    }

}

我的包含head节点的链表类:

代码语言:javascript
复制
public class LL {
    LLNode head;

    public LL(){
        this.head = null;   
    }

    public void insertHead(LLNode input){
        input.next = head;
        this.head = input;
    }

    public void removeFirst(){
        this.head = this.head.next;
    }

    public void removeLast(){
        if (this.head == null || this.head.next == null){
            this.head = null;
            return;
        }
        LLNode current = this.head;
        LLNode tmphead = current;
        while(current.next.next != null){
            current = current.next;
        }
        current.next.next = null;
        this.head = tmphead ;
    }

    public void printAll(){
        LLNode current = this.head;

        while(current != null){
            System.out.print(current.value+" ");
            current = current.next;
        }
        System.out.println();
    }


    public static void main( String[] args){

        LL test = new LL(); 
        LL test2 = new LL();
        String[] eben = {"one","two","three","four","five","six"};

        for(int i =0;i<eben.length;i++){
            test.insertHead(new LLNode(eben[i]));
        }
        test.printAll();
        test.removeFirst();
        test.printAll();
        test.removeLast();
        test.printAll();


    }

}

输出是这样的:

代码语言:javascript
复制
six five four three two one 
five four three two one 
five four three two one 

尽管如此,它还是必须这样:

代码语言:javascript
复制
six five four three two one 
five four three two one 
five four three two

我的实现出了什么问题?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2010-01-10 02:45:29

如果你需要很多代码和/或很多变量来完成这样的任务,你可能已经把自己弄得太复杂了。下面是我将如何使用removeLast()

代码语言:javascript
复制
public void removeLast() {
  // avoid special case: List is empty
  if (this.head != null) {
    if (this.head.next == null) {
      // handle special case: List has only 1 node
      this.head = null;
    } else {
      LLNode prelast = this.head; // points at node before last (eventually)
      while (prelast.next.next != null) prelast = prelast.next;
      prelast.next = null;
    }
  }
}

未经测试的!使用的风险自负。购买价格不退款。

票数 2
EN

Stack Overflow用户

发布于 2010-01-10 02:38:51

current.next.next = null;

应该是

current.next = null;

并且当尝试删除空列表的第一个元素时,实现会失败,并返回NPE

票数 1
EN

Stack Overflow用户

发布于 2010-01-10 02:45:17

while(current.next.next != null)不断进步,直到它成为真的。在这一点上设置current.next.next = null;。事实已经是这样了。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2034444

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档