反转单个链表时的问题

时间:2021-04-11 21:39:39

标签: java linked-list

我想为单个链表实现一个反向函数,但是我在反转我的链表后遇到了一些问题,所以如果我有一个初始链表并且我显示它是正常的,但是如果使用反向方法创建一个新的链表并且显示新的反向链表也正常,但是如果我想显示相同的初始链表,则只显示 firts 参数

这是我的代码

public class LinkedList2 {



    /**
    * Objects of type Node are linked together into linked lists.
    */
    private static class Node {
    int value; // value of an item in the list.
    Node next; // Pointer to the next node in the list.
    }
   




    /**
    * Return a new list containing the same items as the list,
    * but in the reverse order.
    */
    static Node reverse( Node obj ) {

    Node reverse = null; // reverse will be the reversed list
    Node p = obj; // For traversing the list.

    while (p != null) {
        Node temp = p.next;
        p.next = reverse;
        reverse = p;
        p=temp;

    }
    
    return reverse;
    }// end reverse()






   /**
    * Displays the items in the list to which the parameter, first, points.
    * They are printed on one line, separated by spaces
    */
    static void display(Node first) {

    Node p; // For traversing the list.
    p = first;

    int count = 0 ;
    String output = "" ;
    while (p != null){
        
        count+=1;
        output+=Integer.toString(p.value)+"  ";
        p = p.next;
    }

    System.out.println(output);
    
    } // end of display()



   public static void main(String[] args) {

    Node list = null; // A list, initially empty.
    Node reverseList; // The reversed list.
   
    int count = 0; // The number of elements in the list
   
    while (true) {
    // add a new node onto the head of the list before repeating.
    count++;
    if (count == 10)
    break;
    Node head = new Node(); // A new node to add to the list.
    head.value = (int)(Math.random()*10); // A random value.
    head.next = list;
    list = head;
    }
    // Print the current list ; its reverse and the number of zeros in the list using both methods
    //System.out.print("The list: ");
    System.out.print("initial list  ");
    display(list);
    
    reverseList = reverse(list);
    System.out.print("reverse list  ");
    display(reverseList);

    System.out.print("same initial list  ");
    display(list);
     
    }
}

这是输出

initial list  6  0  8  1  9  4  4  5  1  
reverse list  1  5  4  4  9  1  8  0  6  
same initial list  6  

正如你在反转第一个列表后看到的只有一个参数 同样在反向方法中,我只能更改 while 循环内的内容

0 个答案:

没有答案