public class AddTail {
Node head;
public static void main(String[] args) {
AddTail list = new AddTail();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);
System.out.println("链表:");
printList(list.head);
}
// 方法一:只定义head,通过循环找到尾节点,再接上新节点
public void add(int num) {
Node node = new Node(num);
if (this.head == null) {
this.head = node;
} else {
Node p=head;
while(p.next!=null) {
p=p.next;
}
p.next = node;
}
}
//方法二:定义head和tail,head不动,每加入一个新节点就将tail后移一位
public void add2(int num) {
Node node = new Node(num);
if (this.head == null) {
this.head = this.tail = node;
} else {
this.tail.next = node;
this.tail = this.tail.next;
}
}
public static void printList(Node p) {
while (p != null) {
System.out.printf("%d ", p.val);
p = p.next;
}
}
}
数据结构与算法Java版:尾插法建立链表
最新推荐文章于 2022-08-11 15:48:23 发布