简体   繁体   中英

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.

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.

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 . Move head2 ten steps forward keeping head1 at the same place.

Now, after ten steps you have head1 at 0 and head2 at 9th position. Now move both together till head2 hits NULL . Once head2 hits NULL , start moving head1 alone and print each node till head1 reaches 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. Check out the members of the JavaAPIs LinkedList class.

The other members are similar to what is found in the Collections class .

As it stands the easiest solution is as peraueb suggests in the comments follow the print method; ie Do as print does, and store the link to the 10:th to last node. noMAD's idea will work fine there.

The usual way to do it would be to have a LinkedList class handle references / links to the first and the last Node. The Node itself should contain links/references to the previous as well as the next node. This is the suggestion of Nactives answer. Now you are manually dealing with those in 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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