单个链接列表删除任何位置的节点

时间:2018-04-10 14:04:17

标签: visual-c++ singly-linked-list

我编写了一个从位置删除节点的函数,但它删除了下一个节点

deleteAtPosition(int pos)
{
  //pos will be positon of node to be deleted

  Node *pre = head;//points to the head
  Node *curr = head->next;//points to second node
  Node *next = head->next->next;//points to third node


  for(int i=1;i<pos;i++)
  {
     //loop will run until the position is reached 
     //all pointers will be updated
      curr = curr->next;
      pre = pre->next;
      next = next->next;
  }
  //the address of the third node is saved in the next of the first node
  pre->next = next;
  //the middle node is then deleted

  delete curr;
}

0 个答案:

没有答案