简体   繁体   中英

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.

在此处输入图片说明

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;
    }
}

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.

假设您的tail.next == null那么您仍然需要设置front = head就像在以前的情况下更新front

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