题1
//返回有效节点个数
public static int getLength(HeroNode head){
if (head.next==null){
return 0;
}
int length=0;
//定义一个辅助的变量,这里不统计头结点
HeroNode cur=head.next;
while (cur!=null){
length++;
cur=cur.next;
}
return length;
}
题2
//查找单链表中的倒数第k个节点
/**
*思路
* 1.编写一个方法,接受head节点,同时接收一个index
* 2.index表示是倒数第index个节点
* 3.先把链表从头到尾遍历,得到总长度getLength
* 4.得到size后,我们从链表的第一个开始遍历(size-index)个,就可以得到
* 5.如果找到就返回该节点,否则返回空
*/
public static HeroNode findLastIndexNode(HeroNode head,int index){
if(head.next==null){
return null;
}
int size=getLength(head);
if(index<=0||index>size){
return null;
}
//定义一个辅助变量,for循环定位到倒数的index
HeroNode cur=head.next;
for (int i = 0; i <size-index ; i++) {
cur=cur.next;
}
return cur;
}
题3
//将单链表反转
public static void reverseList(HeroNode head){
//如果当前链表为空,或者只有一个节点不用反转'
if(head.next==null||head.next.next==null){
return;
}
HeroNode cur=head.next;
HeroNode next=null;
HeroNode reverseHead=new HeroNode(0,"","");
//遍历原来的链表,将其放到新的链表reverseHead头部
while (cur!=null){
next=cur.next;
cur.next=reverseHead.next;
reverseHead.next=cur;
cur=next;
}
head.next=reverseHead.next;
}
题4
//从尾到头打印单链表 【百度,要求方式 1:反向遍历 。 方式 2:Stack 栈】
//采用方式2
public static void reverse(HeroNode head){
if(head.next==null){
System.out.println("链表空");
}
Stack<HeroNode> stack = new Stack<>();
HeroNode cur=head.next;
while (cur!=null){
stack.push(cur);
cur=cur.next;
}
while (stack.size()>0){
System.out.println(stack.pop());
}
}