package Linke;
public class Test {
public static void main(String[] args) {
Link link=new Link();
PersonNode a=new PersonNode(1,"张三");
PersonNode b=new PersonNode(2,"李四");
PersonNode c=new PersonNode(1,"张三");
PersonNode d=new PersonNode(5,"王五");
PersonNode e=new PersonNode(3,"赵六");
link.add(a);
link.add(b);
link.remove(c);
link.add(d);
link.add(e);
link.print();
link.exchange();
System.out.println("反转后-----------");
link.print();
}
}
class Link{
PersonNode head;
public Link(){
head=new PersonNode();
}
//增添节点
public void add(PersonNode personNode){
PersonNode temp=head;
//将添加进来的节点的next设为null,防止添加一个next已有的节点从而遍历出错
//在反转中,如果不把next设为null,会进入死循环。
personNode.next=null;
//while(true){
//对链表进行遍历
for(;temp.next!=null;temp=temp.next) {
//注释掉的这部分是按no的顺序添加的程序
/* if(temp.next==null){
temp.next=personNode;
break;
}*/
/* if(temp.next.no>personNode.no){
personNode.next=temp.next;
temp.next=personNode;
return;
}*/
//每个人的no都应该不同,防止错误数据进入链表
if(temp.next.no== personNode.no){
System.out.printf("已存在编号为%d的成员\n",personNode.no);
return;
}
//temp=temp.next;
}
temp.next=personNode;
//System.out.println(personNode+"add");
}
//删除节点,根据no来比较判断
public void remove(PersonNode personNode){
PersonNode temp=head;
for(;temp.next!=null;temp=temp.next){
if(temp.next.no==personNode.no){
temp.next=temp.next.next;
return;
}
}
System.out.println("删除节点不存在");
}
//打印链表
public void print(){
for(PersonNode temp=head.next;temp!=null;temp=temp.next){
System.out.println(temp);
}
}
//返回链表的长度(通过一遍遍历)
public int getLength(){
int length=0;
for(PersonNode temp=head;temp.next!=null;temp=temp.next){
length++;
}
//System.out.println("长度为"+length);
return length;
}
//反转方法,先全部入栈,再全部出栈
public void exchange(){
Stack stack=new Stack(20);
for(PersonNode temp=head.next;temp!=null;temp=temp.next){
stack.push(temp);
//System.out.println(temp+"入栈成功");
}
int length=getLength();
//将头结点指向第一个出栈的节点,实现反转的第一步
head.next=stack.pop();
//System.out.println(head.next+"出栈成功");
for(int i=0;i<length-1;i++){
PersonNode temp=stack.pop();
//System.out.println(temp+"出栈成功");
add(temp);
// add(stack.pop());
}
}
}
class Stack{
PersonNode[] personNodes;
int length;
int index;
public Stack() {
}
public Stack(int length) {
personNodes=new PersonNode[length];
this.length = length;
index=-1;
}
public void push(PersonNode personNode){
if(++index>=length){
System.out.println("栈已满"+personNode+"添加失败");
}
personNodes[index]=personNode;
}
public PersonNode pop(){
return personNodes[index--];
}
}
//节点类
class PersonNode{
int no;
String name;
PersonNode next;
public PersonNode() {
}
public PersonNode(int no, String name) {
this.no = no;
this.name = name;
}
//重写toString方法
@Override
public String toString() {
return "PersonNode{" +
"no=" + no +
", name='" + name + '\'' +
'}';
}
}
执行结果: