Loading [MathJax]/jax/output/CommonHTML/config.js
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >是否有办法使这个主类反向方法更有效?可能只需要一个循环?

是否有办法使这个主类反向方法更有效?可能只需要一个循环?
EN

Stack Overflow用户
提问于 2022-10-10 02:50:24
回答 2查看 86关注 0票数 -1
代码语言:javascript
运行
AI代码解释
复制
  //code inside a reverse method that has the list object 
  //passed as a parameter from main method
  int size = list.size();
  //create temporary list object to hold contents of original list in reverse
  MyListReferenceBased temp = new MyListReferenceBased(); 
  for (int i = 0; i < size; i++) 
  { 
    //list add method requires which index your adding to, and object
    //get method just gets the object at the specified index in list
    temp.add(i, list.get((size-i)-1)); 
    //remove method just removes object at specified index
    list.remove((size-i)-1);                       
  } 
  //now that original list is empty, put the contents back in 
  for (int i = 0; i<size; i++)
  { 
    list.add(i, temp.get(i));            
  } 
  temp.removeAll(); 
  //end result: original list is now reversed 
  //and temporary array is all empty 
  System.out.println("List has been Reversed."); 
  //is there a way to get rid of the 2nd loop?? Not possible to just assign?

因此,这段代码位于主类内的反向方法中,用于反转链接列表。一般来说,反转一个列表,因为主类的用户不应该直接与链接列表交互,而只是访问链接列表方法(在链接列表类中没有进行反向操作)。相反,在主/驱动程序类中,我首先创建第二个/临时链接列表,将原始列表中的每个元素(反向)添加到新列表中,从而逆转列表。然后,由于我需要原始列表中的内容,并且只需要在此方法期间使用临时列表,所以我将元素复制回旧列表中。

在此main类的main方法中,将列表对象实例化为本地对象,然后调用反向方法,将列表对象作为参数传递。与第二个循环不同,难道没有一种方法只将临时list对象分配给原始列表吗?当我在列表的底层实现使用数组时,我能够做到这一点,但不知道如何使用链接列表。

或者其他有效率的工作?记住,这是专门用于反转链接列表,而不是直接在链接列表类中。

/全文代码(如有需要)://

代码语言:javascript
运行
AI代码解释
复制
public class MyListReferenceBased implements ListInterface { 

    private Node head; 

    public MyListReferenceBased() 
    {
        head = null;
    }  
    
    public boolean isEmpty() {
        return head == null;
    }

    
    // dont use find()
    public int size() {
        int size = 0;
       
        Node curr = head;
        while (curr != null) {
            curr = curr.getNext(); 
            size++;
        }
    
        return size;
    }

    private Node find (int index) 
    {
        Node curr = head;
        for (int skip = 0; skip < index; skip++) 
        {
            curr = curr.getNext();
        } // end for
        return curr;
    } // end find
    
    public void add(int index, Object item)
                  throws ListIndexOutOfBoundsException 
    {
        if (index >= 0 && index < size() + 1) 
        {
            if (index == 0) 
            {
                // insert the new node containing item at
                // beginning of list
                Node newNode = new Node(item, head);
                head = newNode;
            } 
            else 
            {
                Node prev = find(index-1);
            
                Node newNode = new Node(item, prev.getNext());
                prev.setNext(newNode);
            } // end if
        } 
        else 
        {
            throw new ListIndexOutOfBoundsException(
                          "List index out of bounds exception on add");
        } // end if
    }  // end add
    
        
    public Object get(int index) 
      throws ListIndexOutOfBoundsException 
    {
        if (index >= 0 && index < size()) 
        {
            Node curr = find(index);
            Object dataItem = curr.getItem();
            return dataItem;
        }
        else 
        {
            throw new ListIndexOutOfBoundsException(
                "List index out of bounds exception on get");
        } // end if
    } // end get
    
    public void remove(int index) 
      throws ListIndexOutOfBoundsException 
    {
        if (index >= 0 && index < size()) 
        {
            if (index == 0) 
            {
                head = head.getNext();
            } 
            else 
            {
                Node prev = find(index-1);
                Node curr = prev.getNext(); 
                prev.setNext(curr.getNext());
            } // end if
        } 
        else 
        {
            throw new ListIndexOutOfBoundsException(
                "List index out of bounds exception on remove");
        } // end if
    }   // end remove

    public void removeAll() {
        head = null;
    }
   
    
    public String toString() {
        String x = "";
        
        Node curr = head; 
        int size = size();
        for (int i = 0; i < size ; i++) {
           // curr.getNext(); 
            x += curr.getItem() + " "; 
            curr = curr.getNext(); 
        } 
        return x;
    }
}

//节点类/

代码语言:javascript
运行
AI代码解释
复制
public class Node 
{
  private Object item;
  private Node next;

  public Node(Object newItem) 
  {
    item = newItem;
    next = null;
  } // end constructor

  public Node(Object newItem, Node nextNode) 
  {
    item = newItem;
    next = nextNode;
  } // end constructor

  public void setItem(Object newItem) 
  {
    item = newItem;
  } // end setItem

  public Object getItem() 
  {
    return item;
  } // end getItem

  public void setNext(Node nextNode) 
  {
    next = nextNode;
  } // end setNext

  public Node getNext() 
  {
    return next;
  } // end getNext
} // end class Node
EN

回答 2

Stack Overflow用户

发布于 2022-10-10 03:24:56

那么,将一个又一个节点添加到一个初始空列表中:

代码语言:javascript
运行
AI代码解释
复制
/** Prepend the elements of <code>suffix</code> to <code>suffix</code>,
 *   in reverse order.   
 * @param  emptied  gets, well, <i>emptied</i>
 * @param  suffix
 * @return          <code>suffix</code> with the elements of 
 *                  <code>emptied</code> prepended in reverse order */
static ListInterface 
prependReversed(ListInterface emptied, ListInterface suffix) {
    while (!emptied.isEmpty()) {
        suffix.add(0, emptied.get(0));
        emptied.remove(0);
    }

    return suffix;
}

/** Reverse a List.  
 * @param  emptied  the list to reverse; will be empty on return
 * @return          a <code>MyListReferenceBased</code> containing 
                    the elements of <code>emptied</code> in reverse order */
static MyListReferenceBased reverse_(ListInterface emptied) {
    return prependReversed(emptied, new MyListReferenceBased());
}

/** Reverse a MyListReferenceBased in place (sort of).
 *  Argument is emptied temporarily and restored on return.  
 * @param  toReverse  the list to reverse; will be restored on return
 * @return            a <code>MyListReferenceBased</code> with 
                      the elements of <code>toReverse</code> in reverse order */
public static MyListReferenceBased reverse(ListInterface toReverse) {
    MyListReferenceBased
        reversed = new MyListReferenceBased(),
        saved = new MyListReferenceBased();
    // an O(1) toReverse.clone() or saved.addAll(toReverse) would come in handy
    while (!toReverse.isEmpty()) {
        Object item = toReverse.get(0);
        reversed.add(0, item);
        saved.add(0, item);
        toReverse.remove(0);
    }
    prependReversed(saved, toReverse);
    return reversed;
}

真正的非变异变体(在O(1)时间…中)留作练习。

票数 0
EN

Stack Overflow用户

发布于 2022-10-10 04:00:00

这里是递归实现。

基本大小写:尾巴变成一个新的头,即index参数等于size (或者更大,如果给定的列表为空的话)。

递归案例:

0;

  • invoke

  • 获得了应该使用get()交换的下一个节点,即要从size - 2开始交换的节点索引(因为删除并立即添加尾节点是多余的),并移向1.

remove()以删除当前节点;

  • 使用1.

reverse()递归地传递索引,将新节点添加到尾部。

这就是它的样子:

代码语言:javascript
运行
AI代码解释
复制
public static void reverse(MyListReferenceBased list) {
    reverse(list, 1, list.size()); // initial index is 1 (if the first call would with the index 0 the list would not change its state after the first execution of `reverse()` because we would be dialing with tail node which would stay on the same place)
}

public static void reverse(MyListReferenceBased list, int index, int size) {
    if (index >= size) return; // Base case - tail becomes a head (we don't need to touch the tail)
    
    // recursive case
    Object valueToRemove = list.get(size - 1 - index);
    list.remove(size - 1 - index);
    list.add(size - 1, valueToRemove);
    
    reverse(list, index + 1, size);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74013746

复制
相关文章
函数中*的用法
0904自我总结 函数中*的用法 def fn(a, b, c, *, d=0, x): print(a) print(b) print(c) print(d) print(x) fn(10, 20, 30, x=30, d=100) 这里的*其实相当于一个分界线的作用,前面的是位置形参,后面是关键形参 * 前都是位置参数:无值位置必须赋值,有值位置可以不要赋值,必须在无值位置之后 * 后都是关键字参数:无值关键字必须赋值,有值关键字可以不要赋值,都是指名道姓传参,所
小小咸鱼YwY
2019/09/11
1K0
matlab中fprintf函数的用法举例_matlabfopen函数的用法
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
全栈程序员站长
2022/11/02
6840
matlab中fprintf函数的用法举例_matlabfopen函数的用法
vector中find函数用法_java中set的用法
注意find不属于vector的成员,而存在于算法中,应加上头文件#include <algorithm>:
全栈程序员站长
2022/11/04
1.1K0
c语言findwindowex函数用法,VB中findwindowex函数的用法?
该函数获得一个窗口的句柄,该窗口的类名和窗口名与给定的字符串相匹配。这个函数查找子窗口,从排在给定的子窗口后面的下一个子窗口开始。在查找时不区分大小写。
全栈程序员站长
2022/09/03
8360
python中函数的基础用法
python中的内置函数提供了基础功能,在实际开发中,我们需要将这些基础功能进行搭配组合,来有效解决我们的问题。如何将我们自己构建的代码作为一个可复用的工具,最基本的方法就是写成函数。通过函数可以减少代码冗余,提高编码效率。在python中函数的基本定义如下
生信修炼手册
2020/05/12
6000
python中 apply()函数的用法
用途:当一个函数的参数存在于一个元组或者一个字典中时,用来间接的调用这个函数,并肩元组或者字典中的参数按照顺序传递给参数
狼啸风云
2020/03/31
13.5K0
tensorflow中损失函数的用法
分类问题和回归问题是监督学习的两大种类。这一节将分别介绍分类问题和回归问题中使用到的经典损失函数。分类问题希望解决的是将不同的样本分到事先定义到的经典损失函数。分类问题希望解决的将不同的样本分到事先定义好的类别中。
狼啸风云
2019/01/18
3.8K1
python中count()函数的用法
?
py3study
2020/01/09
1K0
Python中lambda函数的用法
有过编程经验的小伙伴都知道,在其他编程语言如:C#,Java中都有lambda的身影。在Python语言中,同样也有lambda的身影,那就是lambda函数。
软件架构师Michael
2023/02/18
1.1K0
mysql中count()函数的用法
1.下面三种方式,在多数情况下效率是基本相同的,但问题在于,很多情况下,我们数据库可能有脏数据,比如重复数据,或者某条数据重要字段是null的,那下面的这几种,会把这种脏数据也统计上,本质都是统计满足条件的行数的:
IT云清
2019/01/22
3.5K0
python中range()函数的用法
python中range()函数可创建一个整数列表,一般用在for循环中. range()函数语法: range(start,stop[,step])  参数说明: star: 计数从star开始.默认是从0开始. stop: 计数到stop结束,但不包括stop. step: 步长,默认为1. 实例: >>>range(10) # 从 0 开始到 10,没有10 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(1, 11) # 从 1 开始到 11
py3study
2020/01/18
9710
python中reduce函数的用法
reduce:将一个可以迭代的对象应用到两个带有参数的方法上,我们称这个方法为fun,遍历这个可迭代的对象,将其中元素依次作为fun的参数,但是这个函数有两个参数,那些作为参数呢?
用户7886150
2021/01/12
6060
Python中range()函数的用法
start:计数从start开始。默认是从0开始。例如range(5)等价于range(0, 5);
全栈程序员站长
2022/09/07
6710
Python中range()函数的用法
[1009]mysql中Cast()函数的用法
来源:https://blog.csdn.net/m0_37450089/article/details/80750994
周小董
2021/06/29
2K0
SQL中的max()函数用法
select max(score), name, course from score
zcqshine
2020/12/09
2.7K0
SQL中的max()函数用法
python中函数的进阶用法
python支持函数式编程范式,对于函数,还有更加高级的玩法,首先介绍高阶函数的概念。所谓高阶函数,就是可以将函数作为参数输入的一种函数。在python中,常用的高阶函数有以下几种
生信修炼手册
2020/05/12
5170
python中的eval函数的用法_isnan函数
  在Python中eval()函数的语法格式为eval(expression, globals=None, locals=None),注意后面还有globals参数和locals参数。eval()函数用于执行一个字符串表达式,并且返回该表达式的值。与eval相近的有exec函数,该函数将会在另一篇文章详细讲解。
全栈程序员站长
2022/11/01
1.2K0
[1004]mysql中的instr()函数的用法
如图,在abcd字符串中查找是否含有字符串b,返回的字符串位置是2. 说明instr()函数返回的位置是从1开始的,如果找不到则返回0
周小董
2021/06/24
2.4K0
python 中的enumerate()函数的用法
即对一个可遍历的数据对象(如列表、元组或字符串),enumerate会将该数据对象组合为一个索引序列,同时列出数据和数据下标。
Python学习者
2023/06/05
2600
点击加载更多

相似问题

节点-SASS编译器失败- CSS无效

14

SASS无效CSS

12

Sass中的CSS无效

40

Sass无效CSS错误:"expected“

20

节点Sass生成嵌套CSS

11
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档