Question

I'm trying to create a method that adds an int to the end of an existing linked list.

Q: Write a method that takes the head of a list, which is NOT a sentinel node, and an int, n. The method should move the first n nodes to the end of the list while keeping them in the same order. For example, if you had a list [1, 3, 5, 7, 9] and n = 3, your method should return the list: [7, 9, 1, 3, 5] (return the head of the modified list).

Here's what I have, the question is on the addLast method:

public class ListItem{ 
    public int value; 
    public ListItem next; 

    public ListItem(int value, ListItem next){ 
        this.value = value; 
        this.next = next; 
    }

    public void addFirst(int x){
        head = new ListItem(x, head);
        size++
    }

    public void addLast(int x){
        if(head == null){
            addFirst(x);
        }
        else{
            ListItem p;
            for(p = head; p != null; p = p.next){
                p.next = new ListItem(x, null);
                size++;
            }
        }        
}

I'm a little confused as to how the method iterates through the list. In the for loop, it starts at the head, and scrolls until there is no p.next. But the method inside looks like it replaces each p.next with the new list item, rather than scrolling through until the end. What part of the code explains how it skips without adding the new item in each place on the existing list?

Was it helpful?

Solution

Assuming you define head and size attributes;

For addLast function else part should be as follows.

 for(p = head; p.next != null; p = p.next);
 p.next = new ListItem(x, null);
 size++;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top