/**
* 求单链表中节点的个数
* @return
*/
public int countNode(){
int count = 0;
UserNode temp = head.next;
while(true){
if(temp==null){
break;
}
count++;
temp = temp.next;
}
return count; //4
}
/**
* 查找单链表中第k个节点
* @param int index 要查找的第k个节点
* @return
*/
public void findNode(int index){
if(head.next==null){
System.out.println("链表中没有数据");
return;
}
UserNode temp = head.next;
//初始索引
int count = 0;
//是否找到某元素表示
boolean flag = false;
while (true){
//已经遍历到单链表结尾
if(temp==null){
break;
}
count++;
if(count==index) {
flag = true;
System.out.printf("找到第%d个节点为", count);
System.out.println(temp);
break;
}
temp = temp.next;
}
if(!flag){
System.out.println("没有找到");
}
}
关键 int 倒数第n个节点的顺数位置 = 链表中节点数 - n + 1
/**
* 查找单链表中第倒数k个节点
* @param int index 要查找的倒数k个节点
* @return
*/
public void findLastNode(int index){
int singleLength = countNode();//获取链表中的节点数量
//倒数第n个节点的顺数位置
int down = singleLength - index + 1;
UserNode temp = head.next;
//初始索引
int count = 0;
//是否找到某元素表示
boolean flag = false;
while (temp!=null){
//已经遍历到单链表结尾
count++;
if(count==down) {
flag = true;
System.out.printf("倒数%d个节点为", index);
System.out.println(temp);
break;
}
temp = temp.next;
}
if(!flag){
System.out.println("没有找到");
}
}
**第一种方式,利用栈的结构的先进后出的特点 **
import java.util.Stack;
/**
* 从链表末尾还是打印单链表
*/
public void showLastList(){
if(head.next == null){
System.out.println("链表为空");
return;
}
//创建一个栈
Stack<UserNode> stack = new Stack<>();
UserNode temp = head.next;
while (temp!=null){
//入栈
stack.push(temp);
//后移
temp = temp.next;
}
//出栈
while(stack.size() > 0){
System.out.println(stack.pop());
}
}
/**
* 链表反转
*/
public void reverseList(){
//链表为空,或者链表中只有一个节点
if(head.next==null || head.next==null){
return;
}
//如果不为空,那么至少有一个节点
UserNode temp = head.next;
UserNode next = null; //当前节点的下一个节点标识
UserNode newHead = new UserNode(0,"","");
while (temp!=null){
next = temp.next; //记录当前节点的下一个节点标识
temp.next = newHead.next; //将temp的下一个节点指向链表最前端
newHead.next = temp;
//后移
temp = next;
}
//将head.nex域指向newHead.next .实现单链表反转
head.next = newHead.next;
}