给一个链表,进行反转
解题思路每个都插头就行了
public class Main2 { static class Node { int index; Node next; public Node() { } public Node(int index, Node next) { this.index = index; this.next = next; } } static Node init() { Node head = new Node(-1, null); Node tail = new Node(-1, null); Node temp = head; Node cur = head; for (int i = 1; i <= 100; ++i) { temp = new Node(i, null); cur.next = temp; cur = cur.next; } cur.next = tail; return head; } static void print(Node head) { System.out.print(head.index); while (head.next != null) { System.out.print(" " + head.next.index); head = head.next; } System.out.println(); } static Node reverst(Node head) { if (head == null) { return null; } //初始化 /** * head.next表示当前需要移到第一个位置的node,first.next表示新的链表 */ Node first = new Node(); first.next = head; while (head.next != null) { Node next = head.next; head.next = next.next; next.next = first.next; first.next = next; //每次循环完,fist.next是新的表头 // head.next表示需要移动第一个位置的node } //head.next为null,循环结束,表示已经移动完 Node result = first.next; first.next = null; return result; } public static void main(String args[]) { Node head = init(); print(head); head = reverst(head); print(head); } }证明
初始化
head.next表示当前需要移到第一个位置的node,first.next表示新的链表
循环
每次循环完,head.next表示还是当前移到第一个位置的node,first.next还是表示新的链表
结束
head.next为null,循环结束,表示已经移动完