简体   繁体   English

如何将显示方法添加到Java链表实现中,该实现仅显示列表中的前10个项和后10个项?

[英]How to add a display method to a Java Linked List implementation that displays only the first and the last 10 items on the list?

UPDATE: Thanks to all who answered I did what I was assigned to do. 更新:感谢所有回答我所做的工作。 This is really a great forum and I was surprised to find so many helpful and friendly-minded people here :) 这确实是一个很棒的论坛,我很惊讶在这里找到这么多有用和友好的人:)

What I did was to modify the print method in the following way: 我所做的是通过以下方式修改打印方法:

public static void print(ListNode start){

            System.out.println("Printing the first 10 elements on the list:");
            System.out.print("{");

            ListNode previous = start;
            ListNode current = start;

            for (int i = 0; i<10; i++){
                current=current.next;
            }


            for(ListNode node = start; node != current; node = node.next){
                System.out.print(node);
            }
            System.out.println("}");

            System.out.println("Printing the last 10 elements on the list:");
            System.out.print("{");

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

            for(ListNode node = previous; node != current; node = node.next){
                System.out.print(node);
            }

            System.out.println("}");
            System.out.println("End of list");
       }    

END OF UPDATE 更新结束


I'm learning Algorithms and Data structures in Java and I need to add a specific display method to an existing exercise Linked List implementation but I don't know how to do it. 我正在学习Java中的算法和数据结构,我需要向现有的练习链表实现中添加特定的显示方法,但是我不知道该怎么做。

So there is a linked list that contains many items (say thousands) and I need a display method that shows only the first and the last 10 items on the list. 因此,有一个包含许多项目(例如数千个项目)的链接列表, 我需要一种显示方法,该方法仅显示列表中的前10个项目和最后10个项目。

Can you suggest to me a way to do it? 你能给我建议一种方法吗?

The Linked list implementation that I need to work on is the following: 我需要处理的链表实现如下:

import java.util.*;
public class Main {
    public static class ListNode {
      //A linked list node. The data field is represented by the field int data
        //The next item is referenced by the reverence value next

        int data;
        ListNode next;
        public ListNode(){
             this.data = 0; this.next = null;
        }
        public ListNode(int data){
            this();this.data = data;
        }
        public ListNode(int data, ListNode next){
             this.data = data;this.next = next;
        }
        public String toString()    {
             return "[" + this.data + "]";
        }
        //The linked list is referenced by the first node.
        //An empty list is referenced by a null reference.
        //That's why all methods for the list are public static -
        //(null doesn't have methods)

        //Returns the beginning of a list with length "length"and 
        //elements with random values
        public static ListNode generate(int length) {
            ListNode start = null;
            Random rn = new Random();
            for(int i = 0; i < length; i++){
                start = new ListNode(rn.nextInt(10000), start);
            }
            return start;
        }

        //Displays the list to the console from the specified starting point
        public static void print(ListNode start){
            System.out.print("{");
            for(ListNode node = start; node != null; node = node.next){
                System.out.print(node);
            }
            System.out.println("}");
        }

        //Counts how many elements there are in the list
        public static int length(ListNode L){
            int k=0;
            for(;L!=null;k++,L=L.next);
            return k;
        }

        //Returns a node with key searchd if found in the list 
        public static ListNode search(ListNode start, int searchd){
            for(ListNode node = start; node != null; node = node.next){
                if(node.data == searchd){ return node; }
            }
            return null;
        }

        //If a node with the specified key is found in the list L 
        //a new node with the value keyAfter is inserted after it.
        public static void insertAfter(ListNode L, int key, int keyAfter){
            while(L!=null && L.data!=key)L=L.next;
            if(L!=null){
                L.next= new ListNode(keyAfter,L.next);
            }
        }

        //Inserts a node with key "keyBefore" before the node
        //with the specified key

        public static ListNode insertBefore(ListNode L, int key, int keyBefore){
            ListNode p = null, r=L;
            while(L!=null && L.data!=key){
                p=L;L=L.next;
            }
            if(p!=null){
                p.next= new ListNode(keyBefore,p.next);return r;
            }
            else{
                p=new ListNode(keyBefore,L);return p;
            }
        }

        //Inserts a new element with the specified key in a sorted list 
        //with ascending values so that the list remains sorted

        public static ListNode insertOrd(ListNode L, int key){
            ListNode p = null, r=L;
            while(L!=null && L.data<key){
                p=L;L=L.next;
            }
            if(p!=null){
                p.next= new ListNode(key,p.next);return r;
            }
            else{
                p=new ListNode(key,L);return p;
            }
        }

        //Generates a sorted list with a specified lenght
        public static ListNode generateOrd(int length) {
            ListNode start = null;
            Random rn = new Random();
            for(int i = 0; i < length; i++){
                start = insertOrd(start,rn.nextInt(10000));
            }
            return start;
        }

         //Takes two ordered lists and returns a merged and sorted list 
        //that combines the  elements in the original lists

          public static ListNode merge(ListNode a, ListNode b){
            if(a==null)return b;
            if(b==null)return a;
            ListNode r = null;
            if(a.data<=b.data){
                r=a;a=a.next;
            }else{
                r=b;b=b.next;
            }
            ListNode last=r;
            while(a!=null && b!=null){
                if(a.data<=b.data){
                    last.next=a;a=a.next;
                }else{
                    last.next=b;b=b.next;
                }
                last=last.next;
            }
            if(a!=null)last.next=a;else last.next=b;    
            return r;
        }

        //Splits a list evenly and returns the beginning of the 2-nd part

       public static ListNode split(ListNode L){
            int n=length(L)/2;
            ListNode t=L;
            for(int i=0;i<n-1;i++,t=t.next);
            ListNode secPart = t.next;
            t.next=null;
            return secPart;
        }

        //Sorts a list in an ascending order
        public static ListNode mrgSort(ListNode L){
            if(L==null || L.next==null)return L;
            ListNode b = split(L);
            L=mrgSort(L); b= mrgSort(b);
            return merge(L,b);
        }
    };//End of class ListNode

    public static void main(String[] args){

            ListNode a = ListNode.generateOrd(10);
        ListNode.print(a);
            ListNode b = ListNode.generateOrd(10);
        ListNode.print(b);
        a=ListNode.merge(a,b);
        ListNode.print(a);
        b=ListNode.split(a);
        ListNode.print(a);
        ListNode.print(b);
        ListNode c = ListNode.generate(20);
        ListNode.print(c);
        c = ListNode.mrgSort(c);
        ListNode.print(c);
    }

}

Alright, I am not going to write the code for you but ill tell you how to go about doing it. 好吧,我不会为您编写代码,但会告诉您如何去做。

Initially say you have two pointers ( head1 and head2 ) which point to the first node of the list . 首先说您有两个指针( head1 and head2 ),它们指向list的第一个节点。 Move head2 ten steps forward keeping head1 at the same place. 移动head2十步向前保持head1在同一个地方。

Now, after ten steps you have head1 at 0 and head2 at 9th position. 现在,经过十步你head1 0和head2在第9位。 Now move both together till head2 hits NULL . 现在一起移动直到head2达到NULL为止。 Once head2 hits NULL , start moving head1 alone and print each node till head1 reaches head2 . 一旦head2NULL ,开始移动head1独自打印每个节点,直到head1达到head2

Hope this helps 希望这可以帮助

This is a fairly odd implementation of a Linked list. 这是链表的一个相当奇怪的实现。

What sticks out is 突出的是

  • The amount of static members 静态成员数量
  • No class representing the actual list. 没有代表实际列表的类。

The static members in node should be placed in a LinkedList class. 节点中的静态成员应放在LinkedList类中。 Check out the members of the JavaAPIs LinkedList class. 签出JavaAPIs LinkedList类的成员。

The other members are similar to what is found in the Collections class . 其他成员类似于Collections类中的成员

As it stands the easiest solution is as peraueb suggests in the comments follow the print method; 就目前而言,最简单的解决方案是peraueb在注释中建议的遵循打印方法。 ie Do as print does, and store the link to the 10:th to last node. 即执行打印,并将链接存储到第10个节点。 noMAD's idea will work fine there. noMAD的想法在这里可以很好地工作。

The usual way to do it would be to have a LinkedList class handle references / links to the first and the last Node. 通常的方法是让LinkedList类处理对第一个最后一个Node的引用/链接。 The Node itself should contain links/references to the previous as well as the next node. 节点本身应包含到 一个节点和下一个节点的链接/引用。 This is the suggestion of Nactives answer. 这是Nactives答案的建议。 Now you are manually dealing with those in main(...). 现在,您正在手动处理main(...)中的那些。

For that you need a reference to your first and your last item. 为此,您需要参考第一项和最后一项。

Best way is also to make it a duuble linked list: http://en.wikipedia.org/wiki/Doubly_linked_list 最好的方法也是使它成为双链表: http : //en.wikipedia.org/wiki/Doubly_linked_list

Basicly, at the front of your list it is still the same. 基本上,在列表的最前面还是一样。 But now you can also access your list at the end and move to the beginning of your list. 但是现在您也可以在列表的末尾访问列表并移至列表的开头。

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

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