新浪----查找单链表中的倒数第K个节点
思路分析:遍历整个链表,得到链表的总长度size,接着再次遍历(size-k)个即可。
public static Node findNode(Node head,int k){
if(head.next==null){
return null;
}
int size=getLength(head);
if(k<=0||k>size){
return null;
}
//定义辅助变量cur
ode cur=head.next;
for(int i=0;i<size-k;i++){
cur=cur.next;
}
return cur;
}
腾讯—单链表的反转
思路分析:
思路:
- 先定义一个节点 reverseHead = new HeroNode();
- 遍历链表,每遍历一个节点,就将其取出,并放在新的链表reverseHead 的最前端.
- 原来的链表的head.next = reverseHead.next;
public static void reversetList(Node head){
if(head.next==null||head.next.next==null){
return;
}
Node cur=head.next;
Node next=null;
NOde reverseHead=new Node(0,"","");
while(cur!=null){
next=cur.next;//先暂时保存当前节点的下个节点
cur.next=reverseHead.next;//将cur接到新的链表上
cur=next;//后移
}
head.next=reverseHead.next;
}
百度–从尾到头打印单链表
思路:将各个节点压入到栈中,然后利用栈的先进后出的特点,将节点逐个出栈
public static reversePrint(Node head){
if(head.next==null){
retur;
}
Stack<Node>stack=new Stack<Node>();
Node cur=head.next;
while(cur!=null){
stack.push(cur);
cur=cur.next;
}
while(stack.size()>0){
System.out.println(stack.pop());
}
}