简体   繁体   English

Java-使用for循环反转单个LinkedList

[英]Java - Reversing a Singly LinkedList with a for loop

So the challenge right now is to try and take a LinkedList L and create a new LinkedList Reverse with the reverse of L. I need to accomplish this with a forloop. 因此,现在的挑战是尝试使用LinkedList L并创建一个与L反向的新LinkedList反向。我需要使用forloop来完成此任务。 This is what I have so far: 这是我到目前为止的内容:

public void ReverseL(Intco obj) {
    ListNode p = obj.c;
    ListNode RevL = c;
    int index = obj.get_howmany();
    if (obj.c != null) {
        while (this.get_howmany() != obj.get_howmany()) {
            p = obj.c;
            for (int i = index; i <= 0; i--) {
                p = p.link;
            }
            RevL = new ListNode(p.info, RevL);
            howmany++;
            index--;
        }
    }
    c = RevL;
}

Intco is the class I am working with. 我正在与Intco一起上课。 Howmany is the counter for how many integers are in the LinkedList (It is incremented by the insert method I made). Howmany是LinkedList中有多少个整数的计数器(通过我制作的insert方法递增)。

Let's say I add 4 integers to L, so L will contain: L -> 5 -> 12 -> 25 -> 15 -> null 假设我向L添加了4个整数,所以L将包含:L-> 5-> 12-> 25-> 15-> null

howmany = 4 for L. L的howmany = 4。

The forloop is going to go through L until it hits the 4th value, insert that 4th value to RevL. forloop将经过L直到达到第4个值,然后将第4个值插入RevL。 Go through L again, but hits 3rd value (25) now, then insert 3rd value to RevL. 再次经过L,但现在达到第3个值(25),然后将第3个值插入RevL。

The problem I am running into is my output is: 我遇到的问题是我的输出是:

Reverse of L (Reverse): 
15
15
15
15

P: 
15
25
12
5

Just in case, here is the private class for the LinkedList: 以防万一,这是LinkedList的私有类:

private class ListNode {

    private int info;
    private ListNode link;

    public ListNode() {
        info = 0;
        link = null;
    }

    public ListNode(int i, ListNode next) {
        info = i;
        link = next;
    }
}

As you can see, it just repeats the last integer I have in the original linkedlist. 如您所见,它只是重复了我在原始链表中的最后一个整数。 Any help would be appreciated! 任何帮助,将不胜感激!

try change 尝试改变

for (int i = index; i <= 0; i--) {
            p = p.link;
        }

to

for (int i = index; i >= 0; i--) {
            p = p.link;
        }

You can implement a function named get(int index). 您可以实现一个名为get(int index)的函数。 Run the for loop through it. 通过它运行for循环。 This get function will traverse the n, n-1, n-2, ... ,2,1. 此get函数将遍历n,n-1,n-2,...,2,1。

Say you have a list of size 10. Loop goes like this: 假设您有一个大小为10的列表。循环如下所示:

for(int i=size; i>0; i-- {
   get(index);
}

Now how to implement get(int index). 现在如何实现get(int index)。 Since its a singly linked list. 由于它是一个单链表。 There is no way other than to traverse the list from 1st to the desired index. 除了将列表从1遍历到所需索引外,别无其他方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM