求单链表中有效节点的个数
遍历数组,通过length++ 得到有效节点的个数
public static int getLength(Node head
){
int length
=0;
Node temp
=head
.next
;
while (true){
if (temp
!=null
){
length
++;
}else {
break;
}
temp
=temp
.next
;
}
return length
;
}
查找单链表中的倒数第 k 个结点 【新浪面试题】
public static Node
findNodeByk(int k
,LinkedLiset linkedLiset
){
Node head1
= getHead(linkedLiset
);
int lengeth
= getLength(head1
);
if (head1
.next
==null
){
System
.out
.println("链表为空");
return null
;
}
if (k
<0|k
>lengeth
){
System
.out
.println("k非法");
}
Node cur
=head1
;
for (int i
= 0;i
<lengeth
-k
;i
++){
cur
=cur
.next
;
}
return cur
.next
;
}
单链表的反转【腾讯面试题,有点难】
* 思路
* 先创建一个新的头节点
* 遍历原链表
,每取出一个节点
,就把其放在新链表的最前面
*/
public void fanzhuan(){
Node node
=new Node(null
,null
,0);
if (head
.next
==null
|head
.next
.next
==null
){
return;
}
Node temp
=head
.next
;
Node next
=null
;
while (true){
if (temp
==null
){
break;
}
next
=temp
.next
;
temp
.next
=node
.next
;
node
.next
=temp
;
temp
=next
;
}
head
.next
=node
.next
;
}
) 从尾到头打印单链表 【百度,要求方式 1:反向遍历 。 方式 2:Stack 栈】
方式1 会破坏原链表 不建议 方式2:创建Stack对象通过add 和pop方法就可以实现 不做过多讲解