反向单链表Java
发布时间:2020-12-15 07:36:17 所属栏目:Java 来源:网络整理
导读:参见英文答案 How to reverse a singly-linked list in blocks of some given size in O(n) time in place?????????????????????????????????????4个 有人能告诉我为什么我的代码有效吗?我想在java中反转单个链表:这是方法(不能正常工作) public void reve
参见英文答案 >
How to reverse a singly-linked list in blocks of some given size in O(n) time in place?????????????????????????????????????4个
有人能告诉我为什么我的代码有效吗?我想在java中反转单个链表:这是方法(不能正常工作) public void reverseList(){ Node before = null; Node tmp = head; Node next = tmp.next; while(tmp != null){ if(next == null) return; tmp.next = before; before = tmp; tmp = next; next = next.next; } } 这是Node类: public class Node{ public int data; public Node next; public Node(int data,Node next){ this.data = data; this.next = next; } } 在输入4-> 3-> 2-> 1时,我得到了输出4.我调试它并正确设置指针,但我仍然不明白为什么它只输出4. 解决方法Node next = tmp.next; while(tmp != null){ 那么当tmp == null时会发生什么? 但你几乎得到了它. Node before = null; Node tmp = head; while (tmp != null) { Node next = tmp.next; tmp.next = before; before = tmp; tmp = next; } head = before; 或者更好(?)命名: Node reversedPart = null; Node current = head; while (current != null) { Node next = current.next; current.next = reversedPart; reversedPart = current; current = next; } head = reversedPart; ASCII艺术: <__<__<__ __ : reversedPart : head (__)__ __ __ head : current: > > > (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |