标签:public 通过 eve private stat vat while int 分析
通过newList保存当前节点,通过下一次操作把新的节点插入二者之间实现反转。
class Test4 {
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3); // 1 -> 2 -> 3
reverse(head);
}
public static ListNode reverse(ListNode head) {
// core algorithm
ListNode newList = new ListNode(-1);
while (head != null) {
ListNode next = head.next;
head.next = newList.next;
newList.next = head;
head = next;
// print the process
ListNode print = newList;
System.out.println("");
while (null != print) {
System.out.print(print.val + "->");
print = print.next;
}
System.out.print("null");
}
return newList.next;
}
private static class ListNode {
ListNode next = null;
int val;
ListNode(int val) {
this.val = val;
}
}
}
输出结果:
标签:public 通过 eve private stat vat while int 分析
原文地址:https://www.cnblogs.com/alyiacon/p/12543576.html