0

I am working on iterative delete function that deletes node from a linked list, I think that the code is supposed to work fine. But when I can't use "delete" to delete the first Node of the List. The code is: #include using namespace std;

struct Node { int data; Node* next; }; Node* GetNewNode(int data) { Node* newNode = new Node; newNode->data = data; newNode->next = NULL; return newNode; } Node* Insert(Node *root, int data) { if (root == NULL) { root = GetNewNode(data); } else root->next = Insert(root->next, data); return root; } void Delete_k(Node *root, int k) { int i = 0; Node* P = new Node; if (k == 1) { P = root; root = root->next; delete P; } else { for (int i = 1; i <= k - 2; i++) { root = root->next; } root->next = root->next->next; } } void Output(Node* root) { if (root == NULL) { root = root->next; } while (root != NULL) { cout << root->data << " "; root = root->next; } } int main() { int n, a, pos; Node* root = NULL; cout << "Input your list hear: "; cin >> n; while (n > 0) { root = Insert(root, n); cin >> n; } Output(root); cout << "\nDelete Pos?: "; cin >> pos; Delete_k(root, pos); Output(root); } 

I have problem in this

void Delete_k(Node *root, int k) { int i = 0; Node* P = new Node; if (k == 1) { P = root; root = root->next; delete P; } else { for (int i = 1; i <= k - 2; i++) { root = root->next; } root->next = root->next->next; } } 
8
  • Post the test code that doesn't work as expected Commented Sep 28, 2015 at 17:48
  • @JamesWierzba yes, this code doesn't work if you choose 1 to delete. Commented Sep 28, 2015 at 17:52
  • When you used the debugger, which statements are giving you issues? Commented Sep 28, 2015 at 17:53
  • 1
    In output: if (root == NULL) root = root->next; if there is no root, get the next item after the non-existent root. Almost certainly not what you want to do. Commented Sep 28, 2015 at 18:07
  • 1
    Delete_K leaks memory. Commented Sep 28, 2015 at 18:28

1 Answer 1

3

The problem:

void Delete_k(Node *root, int k) 

The value at root is pass by reference, but the pointer to it is not.

Result: Delete_k's root is a copy of main's root. Delete_K's root gets repointed and deleted. Main's root now points at garbage memory. End game program.

Solution:

Provide a reference to the root pointer so that it doesn't get copied.

void Delete_k(Node *& root, int k) 

Or return root from Delete_k.

Node * Delete_k(Node * root, int k) { //existing code return root; } 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for giving me a perfect solution. My problem is solved.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.