• 0

Linked list problem


Question

I'm trying to get this linked list to work, it compiles but then terminates...I think either my insert or remove function is incorrect or at least my logic is off.

struct dNode { 
   int data;
   dNode* prev;
   dNode* next;
};

int main() {
   int k;
   dNode* head = 0;

   cout << "Enter 10 integers: ";
   for (int i = 0; i < 10; i++) {
      cin >> k;
      insert(head, k);
   }

   cout << "Displaying the list: ";
   print(head);

   cout << "Enter an integer k and I will delete the k-th node: ";
   cin >> k;

   dNode* temp = head;

   // move temp to the right k times, so it points to the k-th node.
   // If there are not that many nodes, it stops at the end.
   for (int i = 0; i < k && temp; i++)
      temp = temp -> next;

   if (!temp)
     cout << "There are not that many nodes.\n";
   else remove(head, temp);

   cout << "Displaying the list: ";
   print(head);

   return 0;
}

void print(dNode* p) {
   while (p) {
      cout << p -> data << ' ';
      p = p -> next;
  }
   cout << endl;
}


[b]void insert(dNode*& head, int m) {
struct dNode *newNode;
newNode = new dNode;
data = n;
newNode->next = head->next;
newNode->prev = head;
head->next = newNode;

}[/b]


[b]void remove(dNode*& head, dNode*& node)
{
head->prev = head->next;
node->next->prev =node->prev;
}[/b]

Any suggestions appreciated.

Edited by phantomAI
Link to comment
Share on other sites

1 answer to this question

Recommended Posts

  • 0

Make sure you are not dereferencing any null pointers. You are going to have some special cases when you are inserting and removing.

For example if there is nothing in your list and you say:

pNode->pNext;

and pNext ins't pointing to anything yet, you are goin to get seg fault.

Hope that helps some!

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.