class HeroNode{
public int no;
public String name;
public String nickname;
public HeroNode next;
//构造器
public HeroNode(int no, String name, Stirng nickname){
this.no = no;
this.name = name;
this.nickname = nickname;
}
}
新浪面试题---查找单链表中的倒数第k个节点
思路:
1.编写一个方法,接受head节点,同时接收一个index
2.index表示倒数第index节点
3.先把链表从头到尾遍历,得到链表的节点个数
4.得到size后,从链表的第一个节点开始遍历,遍历 size-index 个节点
//getLength()方法是自己编写的获取链表节点个数方法
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;
}
heroNode cur = head.next;
for(int i = 0; i < size - index; i++){
cur = cur.next;
}
return cur;
}
腾讯面试题---将单链表反转
思路
1.先定义一个节点reverseHead = new HeroNode();
2.从头到尾遍历原来的链表,每遍历一个节点就将其取出,并放在新的链表reverseHead的最前端
3.原来的链表的head.next = reverseHead.next
public static void reversetList(HeroNode head){
//如果当前链表为空或者只有一个节点,无需反转直接返回
if(head.next == null || head.next.next ==null){
return;
}
//
HeroNode cur = head.next;
HeroNode next = null; //当前节点的下一个节点
HeroNode reversHead = new HeroNode(0,"","");
While(cur != null){
next = cur.next;
cur.next = reverseHead.next;
reverseHead.next = cur;
cur = next;
}
head.next = reverseHead.next;
}
百度面试题---从尾到头打印链表
思路:
上面的要求是逆序打印链表
如果先反转再打印会破坏原来的链表不建议
我么可以利用栈这个数据结构,将各个节点压入到栈中,利用栈的先进后出的特点实现逆序打印