用java写一个双向的链表,并用for循环实现
节点类
public class Node {
int data;
Node last;
Node next;
public Node getLast() {
return last;
}
public void setLast(Node last) {
this.last = last;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public Node(int data){
this.data = data;
}
}
实现类
public class Firsttest {
public static void main(String [] asd){
Node no1 = new Node(1);
Node head = no1;
Node tail = null;
for(int i = 1;i<10;i++){
Node temp=new Node(i+1);
no1.setNext(temp);
temp.setLast(no1);
no1=no1.next;
}
tail = no1;
tail.next=head;
System.out.println("====");
for(;tail!=null;tail = tail.getLast())
{
System.out.print(tail.data);
}
}
}
总结
写一个链表要注意几个点
1.这个链表写出来之后是一个链式的结构,需要记录头节点和尾节点。
2.要注意链表的各个节点之间的指向关系
3.在循环添加节点的时候把新节点temp的last和next都记录上

本文详细介绍了如何使用Java实现一个双向链表,包括节点类的设计和实现类的构造。通过for循环添加节点,并确保双向链表的正确指向,最后演示了如何遍历整个链表。
1015

被折叠的 条评论
为什么被折叠?



