[Java语言]实现链表

链表是一个结点指向下一个结点的存储结构,每一个结点有两个元素,一个是存放数据本身,另一个数据指向下一个结点,由这些结点组成一个链表

思路:

  • 需要先定义一个结点类包含两个元素,一个数据,一个指向下一结点
  • 定义一个链表,包含一个头结点的元素
  • 根据链表中头结点中包含下一个结点循环找到最后的结点,在最后增加新的结点

代码实现


public class NodeList {
    
    

   public class Node {
    
    
   	public int data;
   	public Node next;

   	public Node(int data) {
    
    
   		this.data = data;
   		this.next = null;
   	}

   }

   public Node headNode;

   public void add(int data) {
    
    
   	Node node = new Node(data);
   	if (this.headNode == null) {
    
    
   		this.headNode = node;
   	} else {
    
    

   		Node tmp = this.headNode;
   		while (tmp.next != null) {
    
    
   			tmp = tmp.next;
   		}
   		tmp.next = node;
   	}
   }

   public void showall() {
    
    

   	if (this.headNode == null) {
    
    
   		System.out.println("no data");
   	} else {
    
    

   		Node tmp = this.headNode;
   		while (tmp.next != null) {
    
    
   			System.out.println(tmp.data);
   			tmp = tmp.next;
   		}
   		System.out.println(tmp.data);
   	}
   }

   public static void main(String[] args) {
    
    
   	// TODO Auto-generated method stub
   	NodeList nl = new NodeList();
   	nl.add(1);
   	nl.add(2);
   	nl.add(3);
   	nl.add(4);
   	nl.showall();
   }
}

猜你喜欢

转载自blog.csdn.net/q291938895/article/details/109063027