编程语言
首页 > 编程语言> > 反向单链表Java

反向单链表Java

作者:互联网

参见英文答案 > 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:      >  >  >

标签:java,singly-linked-list
来源: https://codeday.me/bug/20190919/1812895.html