package com.it.test1;
public class demo3 {
public void main(String[] args) {
personNode pN1 = new personNode(1);
personNode pN2 = new personNode(2);
personNode pN3 = new personNode(3);
LinkList linkList = new LinkList();
System.out.println("============头插法测试==============");
linkList.headInsert(pN1);
linkList.headInsert(pN2);
linkList.headInsert(pN3);
linkList.list();
/*
System.out.println("============尾插法测试==============");
linkList.endInsert(pN1);
linkList.endInsert(pN2);
linkList.endInsert(pN3);
linkList.list();
*/
}
/**
* 链表
*/
class LinkList{
private personNode head = new personNode();
/**
* 头插法
*/
public void headInsert(personNode node){
//如果链表为空
if(head.getNext() == null){
head.setNext(node);
return;
}
//如果链表不为空
personNode temp = head.next;
head.next = node;
node.next = temp;
}
/**
* 尾插法
*/
public void endInsert(personNode node){
//如果头结点为空
if (head.next == null){
head.next = node;
return;
}
//如果头节点不为空,遍历到最后一个结点
personNode temp = head.next;
while (true) {
if(temp.next == null){
break;//跳出,说明链表有2个结点
}
//temp 的next域 不为空,证明还没有到最后的结点,于是将指针向后移一位
temp = temp.next;
}
temp.next = node;
}
/**
* 遍历单链表
*/
public void list(){
if (head.next == null){
System.out.println("链表为空");
}
personNode temp = head.next;
while (true){
if (temp == null){
// System.out.println(temp);
break;
}
System.out.println(temp);
//temp 后移继续遍历
temp = temp.next;
}
}
}
/**
* 结点
*/
class personNode {
private int data;
private personNode next;
//这里注意有参构造器没有给结点 next赋值
public personNode(int data) {
this.data = data;
}
public personNode() {
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public personNode getNext() {
return next;
}
public void setNext(personNode next) {
this.next = next;
}
@Override
public String toString() {
return "personNode{" +
"data=" + data +
'}';
}
}
}