JavaWannabee
JavaWannabee

Reputation: 91

Removing all nodes from linked list (given a start and an end index)

I'm writing an extra removeRange() method that except a start index and end index as parameters. I've passed all the conditions except when the number of nodes equals the range from start to end.

example my linked list contains:

1 -> 2 -> 3

after the method removeRange(0,2) is called:

list should become null, since from 0 to 2, the count is 3 and there are also 3 elements in my list.

look at the picture for a better idea of what's going on if you can.

enter image description here

Code:

public void removeRange(int start, int end) {
    if(start < 0 || end < 0) {
        throw new IllegalArgumentException();
    } 
    if(start == 0 && end == 0) {
        front = front.next;
    } else if (start == 0 && end == 1) {
        front = front.next.next;
    } else {
        ListNode head = front;
        for(int i = 0; i < start-1;i++) {
            head = head.next;
        }
        ListNode tail = front;
        for(int i = 0; i < end;i++) {
            tail = tail.next;
        }
        head.next = tail.next;
    }
}

Upvotes: 0

Views: 1502

Answers (2)

user3390929
user3390929

Reputation: 68

The best way to code any linked data structures (lists, trees, graphs) is to get a white board, and draw the linked list. Then, for the test input, step through the code one line at a time, just like the computer would execute it. For each line, make the corresponding change on the drawn version. At some point the code will tell you to draw something that you know isn't right, and that tells you where your problem is.

One thing I noticed in your code, is that you don't make sure the input range are withing the size of the list. What if the list is 5 nodes long, and someone calls removeRante(10, 12)?

For this particular problem, you have 4 cases, and you should test for and handle them in this order. . 1. Start = head and End = tail, at which point you make head and tail both null, thus emptying the linked list.
2. Start = head. Move head to point to end + 1. 3. End = tail. Move tail to start - 1.
4. Everything else. Head = start + 1, tail = end - 1.

Upvotes: 2

xlm
xlm

Reputation: 7594

Assuming that your tail.next == null then you still need to set front = head as you have done similarly in your previous cases where you update front.

Upvotes: 1

Related Questions