algorithm - 使用 do While 循环反转 LinkedList

标签 algorithm data-structures

public static ElementL reverse(ElementL element){
        //Implement reverse here

        ElementL previous = null;
        ElementL next = element.next;

        do{
            element.next = previous;
            previous = element;
            element = next;
            next = next.next;
        }while(next!=null);

        return  previous;
    }

最后一个元素被跳过,因为 While 循环中的条件检查下一个元素是否为 null。有人可以建议更改现有代码,以便可以修改 while 中的条件以对所有元素执行反向操作。

作为引用,类 ElementL 的结构

public class ElementL{ 
        ElementL next;
        int data;


        public ElementL(int data){
            this.data = data;
            this.next = null;
        }       
    }   

最佳答案

你可以试试这个逻辑:-

ElementL previous = null;
ElementL next = null;
do {
    next = element.next;
    element.next = previous;
    previous = element;
    element = next;
} while (next != null);

return previous;

您唯一需要注意的是,element 最初不是空的!

关于algorithm - 使用 do While 循环反转 LinkedList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18825590/

相关文章:

c++ - 获取 glFrustum 的坐标

c++ - 检查一个字符串是否是 C++ 中另一个字符串的排列

java - memcached 中的数据结构库

c - 反转每一个交替的 k 个节点

c++ - 用递归函数实现 neper number (e)

algorithm - Ford-Fulkerson 算法和最大流最小割定理

algorithm - 椭圆内的随机点离中心越近的概率越高?

c# - 什么 C# 数据结构支持以下内容?

Scala - TrieMap 与 Vector

ios - iPhone - 为我的应用程序存储数据的最佳方式