package org.codewy.algorithm.reverselinkedlist; public class Node { private String val; private Node next; public Node(String data){ this.val = data; } public String getData() { return val; } public Node getNext() { return next; } public void setNext(Node next) { this.next = next; } @Override public String toString() { return "Node{" + "val=‘" + val + ‘\‘‘ + ‘}‘; } }
方法一:
package org.codewy.algorithm.reverselinkedlist; public class ReverseLinkedList { public static Node reverse(Node node) { Node prev = null; Node current = node; Node next = node.getNext(); while (next != null) { //反转指针 current.setNext(prev); prev = current; current = next; next = next.getNext(); } current.setNext(prev); return current; } public static void main(String[] args) { Node a = new Node("a"); Node b = new Node("b"); Node c = new Node("c"); Node d = new Node("d"); Node e = new Node("e"); a.setNext(b); b.setNext(c); c.setNext(d); d.setNext(e); Node result = reverse(a); while (result != null) { System.out.println(result); result = result.getNext(); } } }
输出结果:
参考博客:
https://blog.csdn.net/shengqianfeng/article/details/99677755
原文:https://www.cnblogs.com/codewy/p/11778548.html