法一:
package Leetcode.ListNode;
/**
* @Author: YCKJ3803
* @Date: 2021/3/2 22:39
* @Description: 反转链表,最经典的题,yyds!!!!
*/
public class ReverseListNode {
private static class ListNode{
int value;
ListNode next;
}
private static ListNode reverseListNode(ListNode head){
ListNode pre = null;
ListNode p = head;
while (p != null){
ListNode next = p.next;
p.next = pre;
pre = p;
p = next;
}
return pre;
}
private static void printListNode(ListNode head) {
while (null != head) {
System.out.print(head.value + "->");
head = head.next;
}
System.out.println("null");
}
public static void main(String[] args) {
ListNode root = new ListNode();
root.value = 1;
root.next = new ListNode();
root.next.value = 2;
root.next.next = new ListNode();
root.next.next.value = 3;
root.next.next.next = new ListNode();
root.next.next.next.value= 4;
root.next.next.next.next = new ListNode();
root.next.next.next.next.value = 5;
printListNode(root);
printListNode(reverseListNode(root));
}
}
法二
import java.util.Stack;
public class Test05<sout> {
public static class ListNode{
int Value;
ListNode next;
}
//用栈
public static void zhan(ListNode root){
Stack<ListNode> stack = new Stack<>();
while ( root != null){
stack.push(root);
root = root.next;
}
ListNode tmp;
while (!stack.isEmpty()){
tmp = stack.pop();
System.out.println(tmp.Value+"");
}
}
//用递归
public static void Rucursion(ListNode root){
if (root!=null){
Rucursion(root.next);
System.out.println(root.Value+"");
}
}
public static void main(String[] args) {
ListNode root = new ListNode();
root.Value = 1;
root.next = new ListNode();
root.next.Value = 2;
root.next.next =new ListNode();
root.next.next.Value = 3;
root.next.next.next = new ListNode();
root.next.next.next.Value = 4;
root.next.next.next.next = new ListNode();
root.next.next.next.next.Value = 5;
// zhan(root);
Rucursion(root);
}
}
参考文献
https://blog.csdn.net/guyuealian/article/details/51119499