反向单链表Java [英] Reverse Singly Linked List Java

查看:121
本文介绍了反向单链表Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我为什么我的代码有效吗?我想要反转java中的单个链表:这是方法(无法正常工作)

Can someone tell me why my code dosent work? I want to reverse a single linked list in java: This is the method (that doesnt work correctly)

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。

On input 4->3->2->1 I got output 4. I debugged it and it sets pointers correctly but still I dont get why it outputs only 4.

推荐答案

Node next = tmp.next;
while(tmp != null){

那么当tmp == null时会发生什么?

So what happens when 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 art:

ASCII art:

        <__<__<__ __ : reversedPart    : head
                 (__)__ __ __
head :   current:      >  >  >

这篇关于反向单链表Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆