这是LinkedList算法的实现。算法将节点插入到初学者,给定节点之后或列表的末尾。package LinkedList;class LinkedList { Node Head; class Node { int data; Node Next; public Node(int d) { data = d; Next = null; } } public void insert(int value) { if (Head ==null) { Head = new Node(value); return; } Node new_node = new Node(value); new_node.Next = Head; Head = new_node; } public void display() { Node a = Head; while (a != null) { System.out.println("value:" + a.data); a = a.Next; } } public void insertMiddle(int valueToInsert, Node prev_node) { if (Head == null) { System.out.println("Cant put value after last node"); } Node new_node = new Node(valueToInsert); new_node.Next = prev_node.Next; prev_node.Next = new_node; } public void last(int value){ Node new_node = new Node(value); if(Head == null){ Head = new Node(value); return; } new_node.Next = null; Node last = Head; while(last != null){ last = last.Next ; } last = new_node; return; }}public class LinkedList_Insertion { public static void main(String[] args) { // TODO Auto-generated method stub LinkedList list = new LinkedList(); list.insert(8); list.insert(20); list.insert(0); list.insertMiddle(999, list.Head.Next); list.display(); System.out.println("--------------"); list.last(10000); list.display(); }}在上面的代码中,在使用方法插入时:public void insert(int value) { if(Head ==null){ Head = new Node(value); return; } Node new_node = new Node(value); new_node.Next = Head; Head = new_node;}我们为什么不使用 Head.next = new_node;我们为什么不使用last.next = new_node;?我经常一次又一次地犯同样的错误。如果有人能澄清这个概念,我将不胜感激。期待你的回复!
添加回答
举报
0/150
提交
取消