从尾到头打印链表
题目
输入一个链表的头结点,从尾到头反过来打印出每个结点的值
思路
思路1:将链表反转,再从头遍历输出
思路2:从头遍历链表并压栈,再打印栈数据
思路3:递归,从尾到头打印
实现代码
//思路1,反转链表
//改变链表结构,将指针反转
public static ListNode reverse1(ListNode headNode){
if(headNode == null)
return null;
ListNode pre = null;
while(headNode != null){
ListNode tmp = headNode.next; //找出下一位
headNode.next = pre; //吧当前的指针指向前面
pre = headNode; //向后移动继续
headNode = tmp;
}
return pre; //pre为新链表的head结点
}
思路2
//不改变链表结构,压入栈中
public static ListNode reverse2(ListNode headNode){
Stack<ListNode> stack = new Stack<ListNode>(); //创建栈
while(headNode.next != null){ //吧结点压入栈(最后一个结点没压)
stack.push(headNode);
headNode = headNode.next;
}
ListNode newHeadNode = headNode; //指向最后一个结点
while(!stack.empty()){ //出栈
headNode.next= stack.pop();
headNode = headNode.next;
}
headNode.next = null;
return newHeadNode;
}
思路3
//递归
public static ListNode reverse3(ListNode headNode){
if(headNode == null || headNode.next == null)
return headNode;
ListNode newHeadNode = reverse3(headNode.next);
headNode.next.next = headNode;
headNode.next = null;
return newHeadNode;
}
测试用例
public static void main(String[] args) {
//构建测试链表
ListNode headNode = new ListNode(1);
ListNode node1 = new ListNode(2);
ListNode node2 = new ListNode(3);
ListNode node3 = new ListNode(4);
ListNode node4 = new ListNode(5);
headNode.next = node1;
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = null;
ListNode reverseListNode = reverse3(headNode);
//打印
while(reverseListNode != null){
System.out.println(reverseListNode.node_value);
reverseListNode = reverseListNode.next;
}
}