简体   繁体   中英

Delete the first element of a linked list

I already searched for equal problems on this page and I found a solution which should work. But I still have the problem that the program does not delete the first element in my list. In the method remove() the head = head.next; should delete the first element.

If I start the program the output is: empty list: [5,7] instead of empty list: [6,7]

Can someone pls tell my whats wrong with the element head or my implementation.

public class HeadList {

    Entry head;
    Entry tail;

    public HeadList() {
        head = null;
        tail = null;
    }

    public  void add(int info) {
        Entry p = new Entry(null, null,info);
        if(head == null && tail == null){
            head = p;
            tail = p;
        }else{
            tail = tail.next = p;
        }
    }

    public int remove(int index) {
         Entry p = head;

            for(int i=1; i < index; i++) {
                p = p.next;
            }
            if(p.next != null && p.next != head){
                int ausgabe = p.elem;
                p.next = p.next.next;
                return ausgabe;
            }else if(index == 0){
                int ausgabe = p.elem;
                head = head.next;
                return ausgabe;
            }
            else return 0;
    }

    private void setHead(Entry newHead) {
        //TODO
    }

    public void reverse() {
        //TODO
    }

    public String toString() {
        String out = "[";
        if (head != null) {
            out += head.elem;
            Entry tmp = head.next;
            while (tmp != null) {
                out = out + "," + tmp.elem;
                tmp = tmp.next;
            }
        }
        out += "]";
        return out;
    }

    public static void main(String[] args) {
        HeadList l = new HeadList();
        l.add(5);
        l.add(6);
        l.add(7);
        l.remove(0);
        System.out.println("empty list: " + l);
        // Test implementation
    }

    class Entry {

        Entry first;
        Entry next;
        int elem;

        public Entry(Entry first, Entry next, int elem) {
            this.first = first;
            this.next = next;
            this.elem = elem;
        }
    }
}

I got it! Change the if-Function in remove() method to (p.next != null && index != 0)

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