简体   繁体   English

Java中的链表实现

[英]Linked List Implementation in Java

I came across a sample program that adds numbers to linked list 我遇到了一个向链接列表添加数字的示例程序

import java.util.LinkedList;

class Node {
    public int data;
    public Node next;
    Node(int d){
        data=d;
    }
    public static void main(String args[]){
        LinkList f1 = new LinkList();
        for(int j=0;j<=10;j++){
        f1.inject(j);
        }
        f1.display();
    }

}
class LinkList {
    Node firstlink;
    LinkList(){
        firstlink=null;
    }
    void inject(int a){
     Node pw=new Node(a);
        pw.next=firstlink;
        firstlink=pw;
    }
    void display(){
       Node pw=firstlink;
        while(pw !=null){
            System.out.println(pw.data);
            pw=pw.next;
        }
    }

}

I have some doubt regarding how it's implemented here . 我对它在此处的实现方式有疑问。 first how does 首先如何

Node pw=new Node(a);
        pw.next=firstlink;
        firstlink=pw;

adds item to linked list ? 将项目添加到链接列表? and why statement 以及为什么陈述

Node pw=firstlink;

what does it do ? 它有什么作用 ?

and how will we delete item from linked list? 以及如何从链接列表中删除项目?

Injecting element to LinkedList?

The way it is done is every time inject is called new Node is created with the provided integer value. 完成的方式是每次调用注入时都会使用提供的整数值创建新节点。

Node pw=new Node(a);

This newly create Node instance is made to point to the current Head Node 使这个新创建的Node实例指向当前的Head Node

pw.next=firstlink;

and then then the new instance created is made the new Node. 然后将创建的新实例作为新节点。

firstlink=pw;

As you know in LinkedList all we have to do is maintain the Head Node. 如您所知,在LinkedList中,我们要做的就是维护头节点。 To iterate we simply call next() till != null . 要进行迭代,我们只需调用next()直到!= null In the sample code firstlink represents the Head Node. 在示例代码中, firstlink代表头节点。

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

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