<p>Is it possible to delete a middle node in the single linked list when the only information available we have is the pointer to the node to be deleted and not the pointer to the previous node?After deletion the previous node should point to the node next to deleted node. </p>

[{'answer_id': 69214, 'author': 'Steven A. Lowe', 'author_id': 9345, 'author_profile': 'https://Stackoverflow.com/users/9345', 'pm_score': 0, 'selected': False, 'text': "<p>yes, but you can't delink it. If you don't care about corrupting memory, go ahead ;-)</p>\n"}, {'answer_id': 69220, 'author': 'Allen', 'author_id': 6043, 'author_profile': 'https://Stackoverflow.com/users/6043', 'pm_score': 1, 'selected': False, 'text': "<p>Not if you want to maintain the traversability of the list. You need to update the previous node to link to the next one.</p>\n\n<p>How'd you end up in this situation, anyway? What are you trying to do that makes you ask this question?</p>\n"}, {'answer_id': 69229, 'author': 'owenmarshall', 'author_id': 9806, 'author_profile': 'https://Stackoverflow.com/users/9806', 'pm_score': 0, 'selected': False, 'text': '<p>Yes, but your list will be broken after you remove it.</p>\n\n<p>In this specific case, traverse the list again and get that pointer! In general, if you are asking this question, there probably exists a bug in what you are doing.</p>\n'}, {'answer_id': 69232, 'author': 'Allan Wind', 'author_id': 9706, 'author_profile': 'https://Stackoverflow.com/users/9706', 'pm_score': 2, 'selected': False, 'text': '<p>The initial suggestion was to transform:</p>\n\n<p>a -> b -> c</p>\n\n<p>to:</p>\n\n<p>a ->, c</p>\n\n<p>If you keep the information around, say, a map from address of node to address of the next node then you can fix the chain the next time to traverse the list.  If need to delete multiple items before the next traversal then you need to keep track of the order of deletes (i.e. a change list).</p>\n\n<p>The standard solution is consider other data structures like a skip list.</p>\n'}, {'answer_id': 69234, 'author': 'Kimbo', 'author_id': 10960, 'author_profile': 'https://Stackoverflow.com/users/10960', 'pm_score': 1, 'selected': False, 'text': "<p>You'll have to march down the list to find the previous node.  That will make deleting in general O(n**2).  If you are the only code doing deletes, you may do better in practice by caching the previous node, and starting your search there, but whether this helps depends on the pattern of deletes.</p>\n"}, {'answer_id': 69235, 'author': 'Eltariel', 'author_id': 584, 'author_profile': 'https://Stackoverflow.com/users/584', 'pm_score': 0, 'selected': False, 'text': "<p>In order to get to the previous list item, you would need to traverse the list from the beginning until you find an entry with a <code>next</code> pointer that points to your current item. Then you'd have a pointer to each of the items that you'd have to modify to remove the current item from the list - simply set <code>previous-&gt;next</code> to <code>current-&gt;next</code> then delete <code>current</code>.</p>\n\n<p>edit: Kimbo beat me to it by less than a minute!</p>\n"}, {'answer_id': 69236, 'author': 'perimosocordiae', 'author_id': 10601, 'author_profile': 'https://Stackoverflow.com/users/10601', 'pm_score': 2, 'selected': False, 'text': '<p>Maybe do a soft delete? (i.e., set a "deleted" flag on the node) You can clean up the list later if you need to.</p>\n'}, {'answer_id': 69240, 'author': 'Joe Hildebrand', 'author_id': 8388, 'author_profile': 'https://Stackoverflow.com/users/8388', 'pm_score': 2, 'selected': False, 'text': '<p>One approach would be to insert a null for the data.  Whenever you traverse the list, you keep track of the previous node.  If you find null data, you fix up the list, and go to the next node.</p>\n'}, {'answer_id': 69247, 'author': 'DJ Capelis', 'author_id': 10943, 'author_profile': 'https://Stackoverflow.com/users/10943', 'pm_score': 0, 'selected': False, 'text': '<p>You could do delayed delinking where you set nodes to be delinked out of the list with a flag and then delete them on the next proper traversal.  Nodes set to be delinked would need to be properly handled by the code that crawls the list.</p>\n\n<p>I suppose you could also just traverse the list again from the beginning until you find the thing that points to your item in the list.  Hardly optimal, but at least a much better idea than delayed delinking.</p>\n\n<p>In general, you should know the pointer to the item you just came from and you should be passing that around.</p>\n\n<p>(Edit: Ick, with the time it took me to type out a fullish answer three gazillion people covered almost all the points I was going to mention. :()</p>\n'}, {'answer_id': 69289, 'author': 'Paul', 'author_id': 11012, 'author_profile': 'https://Stackoverflow.com/users/11012', 'pm_score': 0, 'selected': False, 'text': '<p>The only sensible way to do this is to traverse the list with a couple of pointers until the leading one finds the node to be deleted, then update the next field using the trailing pointer.</p>\n\n<p>If you want to delete random items from a list efficiently, it needs to be doubly linked. If you want take items from the head of the list and add them at the tail, however, you don\'t need to doubly link the whole list. Singly link the list but make the next field of the last item on the list point to the first item on the list. Then make the list "head" point to the tail item (not the head). It is then easy to add to the tail of the list or remove from the head.</p>\n'}, {'answer_id': 69306, 'author': 'Ben Combee', 'author_id': 1323, 'author_profile': 'https://Stackoverflow.com/users/1323', 'pm_score': 5, 'selected': False, 'text': "<p>Let's assume a list with the structure</p>\n\n<p>A -> B -> C -> D</p>\n\n<p>If you only had a pointer to B and wanted to delete it, you could do something like</p>\n\n<pre><code>tempList = B-&gt;next;\n*B = *tempList;\nfree(tempList);\n</code></pre>\n\n<p>The list would then look like</p>\n\n<p>A -> B -> D</p>\n\n<p>but B would hold the old contents of C, effectively deleting what was in B.  This won't work if some other piece of code is holding a pointer to C.  It also won't work if you were trying to delete node D.  If you want to do this kind of operation, you'll need to build the list with a dummy tail node that's not really used so you guarantee that no useful node will have a NULL next pointer.  This also works better for lists where the amount of data stored in a node is small.  A structure like</p>\n\n<pre><code>struct List { struct List *next; MyData *data; };\n</code></pre>\n\n<p>would be OK, but one where it's</p>\n\n<pre><code>struct HeavyList { struct HeavyList *next; char data[8192]; };\n</code></pre>\n\n<p>would be a bit burdensome.</p>\n"}, {'answer_id': 69321, 'author': 'Charles Graham', 'author_id': 7705, 'author_profile': 'https://Stackoverflow.com/users/7705', 'pm_score': 0, 'selected': False, 'text': '<p>You have the head of the list, right?  You just traverse it.</p>\n\n<p>Let\'s say that your list is pointed to by "head" and the node to delete it "del".</p>\n\n<p>C style pseudo-code (dots would be -> in C):</p>\n\n<pre><code>prev = head\nnext = prev.link\n\nwhile(next != null)\n{\n  if(next == del)\n  {\n    prev.link = next.link;\n    free(del);\n    del = null;\n    return 0;\n  }\n  prev = next;\n  next = next.link;\n}\n\nreturn 1;\n</code></pre>\n'}, {'answer_id': 69333, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 6, 'selected': False, 'text': "<p>It's definitely more a quiz rather than a real problem. However, if we are allowed to make some assumption, it can be solved in O(1) time. To do it, the strictures the list points to must be copyable. The algorithm is as the following:</p>\n\n<p>We have a list looking like: ... -> Node(i-1) -> Node(i) -> Node(i+1) -> ... and we need to delete Node(i).</p>\n\n<ol>\n<li>Copy data (not pointer, the data itself) from Node(i+1) to Node(i), the list will look like:  ... -> Node(i-1) -> Node(i+1) -> Node(i+1) -> ...</li>\n<li>Copy the NEXT of second Node(i+1) into a temporary variable.</li>\n<li>Now Delete the second Node(i+1), it doesn't require pointer to the previous node.</li>\n</ol>\n\n<p>Pseudocode:</p>\n\n<pre><code>void delete_node(Node* pNode)\n{\n    pNode-&gt;Data = pNode-&gt;Next-&gt;Data;  // Assume that SData::operator=(SData&amp;) exists.\n    Node* pTemp = pNode-&gt;Next-&gt;Next;\n    delete(pNode-&gt;Next);\n    pNode-&gt;Next = pTemp;\n}\n</code></pre>\n\n<p>Mike.</p>\n"}, {'answer_id': 69401, 'author': 'DarenW', 'author_id': 10468, 'author_profile': 'https://Stackoverflow.com/users/10468', 'pm_score': 1, 'selected': False, 'text': '<p>Given</p>\n\n<p>A -> B -> C -> D</p>\n\n<p>and a pointer to, say, item B, you would delete it by<br>\n1. free any memory belonging to members of B<br>\n2. copy the contents of C into B  (this includes its "next" pointer)<br>\n3. delete the entire item C  </p>\n\n<p>Of course, you\'ll have to be careful about edge cases, such as working on lists of one item.</p>\n\n<p>Now where there was B, you have C and the storage that used to be C is freed.</p>\n'}, {'answer_id': 1000807, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 0, 'selected': False, 'text': '<p>The following code will create a LL, n then ask the user to give the pointer to the node to be deleted. it will the print the list after deletion\nIt does the same thing as is done by copying the node after the node to be deleted, over the node to be deleted and then delete the next node of the node to be deleted.\ni.e</p>\n\n<p>a-b-c-d</p>\n\n<p>copy c to b and free c so that result is</p>\n\n<p>a-c-d</p>\n\n<pre><code>struct node  \n{\n    int data;\n    struct node *link;\n };\n\nvoid populate(struct node **,int);\n\nvoid delete(struct node **);\n\nvoid printlist(struct node **);\n\nvoid populate(struct node **n,int num)\n{\n\n    struct node *temp,*t;\n    if(*n==NULL)\n    {\n        t=*n;\n        t=malloc(sizeof(struct node));\n        t-&gt;data=num;\n        t-&gt;link=NULL;\n        *n=t;\n    }\n    else\n    {\n        t=*n;\n        temp=malloc(sizeof(struct node));\n        while(t-&gt;link!=NULL)\n            t=t-&gt;link;\n        temp-&gt;data=num;\n        temp-&gt;link=NULL;\n        t-&gt;link=temp;\n    }\n}\n\nvoid printlist(struct node **n)\n{\n    struct node *t;\n    t=*n;\n    if(t==NULL)\n        printf("\\nEmpty list");\n\n    while(t!=NULL)\n    {\n        printf("\\n%d",t-&gt;data);\n        printf("\\t%u address=",t);\n        t=t-&gt;link;\n    }\n}\n\n\nvoid delete(struct node **n)\n{\n    struct node *temp,*t;\n    temp=*n;\n    temp-&gt;data=temp-&gt;link-&gt;data;\n    t=temp-&gt;link;\n    temp-&gt;link=temp-&gt;link-&gt;link;\n    free(t);\n}    \n\nint main()\n{\n    struct node *ty,*todelete;\n    ty=NULL;\n    populate(&amp;ty,1);\n    populate(&amp;ty,2);\n    populate(&amp;ty,13);\n    populate(&amp;ty,14);\n    populate(&amp;ty,12);\n    populate(&amp;ty,19);\n\n    printf("\\nlist b4 delete\\n");\n    printlist(&amp;ty);\n\n    printf("\\nEnter node pointer to delete the node====");\n    scanf("%u",&amp;todelete);\n    delete(&amp;todelete);\n\n    printf("\\nlist after delete\\n");\n    printlist(&amp;ty);\n\n    return 0;\n}\n</code></pre>\n'}, {'answer_id': 2306642, 'author': 'Aneesh', 'author_id': 278188, 'author_profile': 'https://Stackoverflow.com/users/278188', 'pm_score': 0, 'selected': False, 'text': '<pre><code>void delself(list *list)\n{\n   /*if we got a pointer to itself how to remove it...*/\n   int n;\n\n   printf("Enter the num:");\n\n   scanf("%d",&amp;n);\n\n   while(list-&gt;next!=NULL)\n   {\n       if(list-&gt;number==n) /*now pointer in node itself*/\n       {\n           list-&gt;number=list-&gt;next-&gt;number;\n           /*copy all(name,rollnum,mark..) data of next to current, disconect its next*/\n           list-&gt;next=list-&gt;next-&gt;next;\n       }\n       list=list-&gt;next;\n   }\n}\n</code></pre>\n'}, {'answer_id': 2306670, 'author': 'Aneesh', 'author_id': 278188, 'author_profile': 'https://Stackoverflow.com/users/278188', 'pm_score': 0, 'selected': False, 'text': '<pre><code>void delself(list *list)\n{\n   /*if we got a pointer to itself how to remove it...*/\n   int n;\n\n   printf("Enter the num:");\n   scanf("%d",&amp;n);\n\n   while(list-&gt;next!=NULL)\n   {\n      if(list-&gt;number==n) /*now pointer in node itself*/\n      {\n         list-&gt;number=list-&gt;next-&gt;number;   /*copy all(name,rollnum,mark..)\n                             data of next to current, disconnect its next*/\n         list-&gt;next=list-&gt;next-&gt;next;\n      }\n      list=list-&gt;next;\n   }\n}\n</code></pre>\n'}, {'answer_id': 3635670, 'author': 'Smitha', 'author_id': 438945, 'author_profile': 'https://Stackoverflow.com/users/438945', 'pm_score': 0, 'selected': False, 'text': '<p>If you have a linked list A -> B -> C -> D and a pointer to node B. If you have to delete this node you can copy the contents of node C into B, node D into C and delete D. But we cannot delete the node as such in case of a singly linked list since if we do so, node A will also be lost. Though we can backtrack to A in case of doubly linked list.</p>\n\n<p>Am I right? </p>\n'}, {'answer_id': 4545555, 'author': 'codaddict', 'author_id': 227665, 'author_profile': 'https://Stackoverflow.com/users/227665', 'pm_score': 4, 'selected': False, 'text': '<p>Not possible.</p>\n\n<p>There are hacks to mimic the deletion. </p>\n\n<p>But none of then will actually delete the node the pointer is pointing to.</p>\n\n<p>The popular solution of deleting the <strong>following</strong> node and copying its contents to the <strong>actual</strong> node to be deleted has side-effects if you have <strong>external pointers</strong> pointing to nodes in the list, in which case an external pointer pointing to the following node will become dangling.</p>\n'}, {'answer_id': 8527869, 'author': 'Alex B', 'author_id': 583972, 'author_profile': 'https://Stackoverflow.com/users/583972', 'pm_score': 3, 'selected': False, 'text': '<p>I appreciate the ingenuity of this solution (deleting the next node), but it does not answer the problem\'s question. If this is the actual solution, the correct question should be "delete from the linked list the VALUE contained in a node on which the pointer is given".  But of course, the correct question gives you a hint on solution.\nThe problem as it is formulated, is intended to confuse the person (which in fact has happened to me, especially because the interviewer did not even mention that the node is in the middle).</p>\n'}, {'answer_id': 11534729, 'author': 'Sandeep Mathias', 'author_id': 1533689, 'author_profile': 'https://Stackoverflow.com/users/1533689', 'pm_score': 2, 'selected': False, 'text': "<p>The best approach is still to copy the data of the next node into the node to be deleted, set the next pointer of the node to the next node's next pointer, and delete the next node.</p>\n\n<p>The issues of external pointers pointing to the node to be deleted, while true, would also hold for the next node. Consider the following linked lists:</p>\n\n<p>A->B->C->D->E->F and G->H->I->D->E->F</p>\n\n<p>In case you have to delete node C (in the first linked list), by the approach mentioned, you will delete node D after copying the contents to node C. This will result in the following lists:</p>\n\n<p>A->B->D->E->F and G->H->I->dangling pointer.</p>\n\n<p>In case you delete the NODE C completely, the resulting lists will be:</p>\n\n<p>A->B->D->E->F and G->H->I->D->E->F.</p>\n\n<p>However, if you are to delete the node D, and you use the earlier approach, the issue of external pointers is still there.</p>\n"}, {'answer_id': 13522571, 'author': 'Vinay Kumar Baghel', 'author_id': 685692, 'author_profile': 'https://Stackoverflow.com/users/685692', 'pm_score': -1, 'selected': False, 'text': '<pre><code>Void deleteMidddle(Node* head)\n{\n     Node* slow_ptr = head;\n     Node* fast_ptr = head;\n     Node* tmp = head;\n     while(slow_ptr-&gt;next != NULL &amp;&amp; fast_ptr-&gt;next != NULL)\n     {\n        tmp = slow_ptr;\n        slow_ptr = slow_ptr-&gt;next;\n        fast_ptr = fast_ptr-&gt;next-&gt;next;\n     }\n     tmp-&gt;next = slow_ptr-&gt;next;\n     free(slow_ptr);\n    enter code here\n\n}\n</code></pre>\n'}, {'answer_id': 15356392, 'author': 'Desyn8686', 'author_id': 2159985, 'author_profile': 'https://Stackoverflow.com/users/2159985', 'pm_score': 0, 'selected': False, 'text': '<p>This is a piece of code I put together that does what the OP was asking for, and can even delete the last element in the list (not in the most elegant way, but it gets it done). Wrote it while learning how to use linked lists. Hope it helps.</p>\n\n<pre><code>#include &lt;cstdlib&gt;\n#include &lt;ctime&gt;\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n\nusing namespace std;\n\n\nstruct node\n{\n    int nodeID;\n    node *next;\n};\n\nvoid printList(node* p_nodeList, int removeID);\nvoid removeNode(node* p_nodeList, int nodeID);\nvoid removeLastNode(node* p_nodeList, int nodeID ,node* p_lastNode);\n\nnode* addNewNode(node* p_nodeList, int id)\n{\n    node* p_node = new node;\n    p_node-&gt;nodeID = id;\n    p_node-&gt;next = p_nodeList;\n    return p_node;\n}\n\nint main()\n{\n    node* p_nodeList = NULL;\n    int nodeID = 1;\n    int removeID;\n    int listLength;\n    cout &lt;&lt; "Pick a list length: ";\n    cin &gt;&gt; listLength;\n    for (int i = 0; i &lt; listLength; i++)\n    {\n        p_nodeList = addNewNode(p_nodeList, nodeID);\n        nodeID++;\n    }\n    cout &lt;&lt; "Pick a node from 1 to " &lt;&lt; listLength &lt;&lt; " to remove: ";\n    cin &gt;&gt; removeID;\n    while (removeID &lt;= 0 || removeID &gt; listLength)\n    {\n        if (removeID == 0)\n        {\n            return 0;\n        }\n        cout &lt;&lt; "Please pick a number from 1 to " &lt;&lt; listLength &lt;&lt; ": ";\n        cin &gt;&gt; removeID;\n    }\n    removeNode(p_nodeList, removeID);\n    printList(p_nodeList, removeID);\n}\n\nvoid printList(node* p_nodeList, int removeID)\n{\n    node* p_currentNode = p_nodeList;\n    if (p_currentNode != NULL)\n    {\n        p_currentNode = p_currentNode-&gt;next;\n        printList(p_currentNode, removeID);\n        if (removeID != 1)\n        {\n            if (p_nodeList-&gt;nodeID != 1)\n            {\n                cout &lt;&lt; ", ";\n            }\n\n            cout &lt;&lt; p_nodeList-&gt;nodeID;\n        }\n        else\n        {\n            if (p_nodeList-&gt;nodeID !=2)\n            {\n                cout &lt;&lt; ", ";\n            }\n            cout &lt;&lt; p_nodeList-&gt;nodeID;\n        }\n    }\n}\n\nvoid removeNode(node* p_nodeList, int nodeID)\n{\n    node* p_currentNode = p_nodeList;\n    if (p_currentNode-&gt;nodeID == nodeID)\n    {\n        if(p_currentNode-&gt;next != NULL)\n        {\n            p_currentNode-&gt;nodeID = p_currentNode-&gt;next-&gt;nodeID;\n            node* p_temp = p_currentNode-&gt;next-&gt;next;\n            delete(p_currentNode-&gt;next);\n            p_currentNode-&gt;next = p_temp;\n        }\n        else\n        {\n            delete(p_currentNode);\n        }\n    }\n    else if(p_currentNode-&gt;next-&gt;next == NULL)\n    {\n        removeLastNode(p_currentNode-&gt;next, nodeID, p_currentNode);\n    }\n    else\n    {\n        removeNode(p_currentNode-&gt;next, nodeID);\n    }\n}\n\nvoid removeLastNode(node* p_nodeList, int nodeID ,node* p_lastNode)\n{\n    node* p_currentNode = p_nodeList;\n    p_lastNode-&gt;next = NULL;\n    delete (p_currentNode);\n}\n</code></pre>\n'}, {'answer_id': 58032707, 'author': 'Ankit Raj', 'author_id': 5494644, 'author_profile': 'https://Stackoverflow.com/users/5494644', 'pm_score': 1, 'selected': False, 'text': '<p>Considering below linked list</p>\n\n<blockquote>\n  <p>1 -> 2 -> 3 -> NULL</p>\n  \n  <p>Pointer to node 2 is given say "ptr".</p>\n</blockquote>\n\n<p>We can have pseudo-code which looks something like this:</p>\n\n<pre><code>struct node* temp = ptr-&gt;next;\nptr-&gt;data = temp-&gt;data;\nptr-&gt;next = temp-&gt;next;\nfree(temp);\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/69209', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7086/']