0

My program crashes after sequence of inserting head, then inserting tail, every other cases it seems to work. I cant figure it out.

struct Node {
    int key;
    Node *next;
};

struct List {
    Node *head, *tail;
};

void init(List& l) {
    l.head = l.tail = NULL;
}

void insertHead(List& l, int x) {
    Node *temp=new Node;
    temp->next=NULL;
    temp->key=x;
    temp->next=l.head;
    l.head=temp;
}

void insertTail(List& l, int x) {
    Node *temp=new Node;
    temp->key=x;
    temp->next=NULL;
    if(l.head==NULL) {
        l.head = temp;
        l.tail = temp;
    } else {
        l.tail->next=temp;
        l.tail=temp;
    }
}

Thats only part of my code, but I think it will be enough, otherwise here is remaining part http://pastebin.com/WxmYJ0uE

2
  • It seems that the error is in the remaining part, had a quick look through it and didn't spot it yet. But you have a lot of noise in your code, like the line temp->next=NULL; in the insertHead above, try cleaning up your code, and it will be a lot easier for you or any other person to fix your code. Commented Mar 15, 2017 at 12:50
  • Make a test with an empty list, insertHead, then insertTail. Run it in your debugger. Commented Mar 15, 2017 at 12:56

1 Answer 1

2

You forgot to set the tail when the first element in the list in inserted.

void insertHead(List& l, int x) {
    Node *temp=new Node;
    temp->next=NULL;
    temp->key=x;
    temp->next=l.head;
    l.head=temp;

    if(l.tail == NULL) l.tail = l.head; // <-- you forgot this
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.