【Java 算法实现】链表反转(迭代法)
这个反转方法采用的是迭代方式,它逐个将原链表的节点移动到新链表的头部
public class LinkedList {// 定义链表节点static class Node {int value;Node next;Node(int value) {this.value = value;this.next = null;}}// 反转链表的方法public Node reverseList(Node head) {Node prev = null;Node current = head;while (current != null) {Node nextTemp = current.next; // 保存下一个节点current.next = prev; // 反转当前节点prev = current; // 移动prev到当前节点current = nextTemp; // 继续到下一个节点}return prev; // 新的头节点是prev}// 用于打印链表的辅助方法public void printList(Node node) {while (node != null) {System.out.print(node.value + " ");node = node.next;}System.out.println();}// 主方法,用于测试链表反转public static void main(String[] args) {LinkedList list = new LinkedList();Node head = new Node(1);head.next = new Node(2);head.next.next = new Node(3);head.next.next.next = new Node(4);System.out.println("Original List:");list.printList(head);head = list.reverseList(head);System.out.println("Reversed List:");list.printList(head);}
}
时间复杂度为 O(n),空间复杂度为 O(1)