Can we delete the last node of a Single Linked list if we only know the address of last node

陌路散爱 提交于 2019-12-25 07:48:47

问题


// Variables

typedef struct node 
 { 
    int value; 
    struct node *next; 
 }mynode;

// Globals (not required, though).

mynode *head, *tail, *temp; 

// Functions

void add(int value);

// Function to add new nodes to the linked list

 void add(int value)
 {
    temp = (mynode *) malloc(sizeof(struct node));
    temp->next=(mynode *)0;
    temp->value=value;

    if(head==(mynode *)0)
    {
       head=temp;
       tail=temp;
    }
    else
    {
      tail->next=temp;
      tail=temp;
    }
 }

// The main() function

int main()
 {
     head=(mynode *)0;

     // Construct the linked list.
     add(1);
     add(2);
     add(3);

     return(0);
 }

If I only have a pointer to a node, whose value is 3(The Last node as seen in the aforementioned code) , Can we delete it and make a node whose value is 2(aforementioned code) as the last node.


回答1:


No, but if you know what you are doing, you can modify the last node in-place. Deleting the last node requires access to the second-to-last node, and specifically its link to the last node.




回答2:


No you can not. Unless you have some reference to previous node. like head pointer. If you have other reference than its pretty much easier. In fact if you don't have any pointers you will loose the list itself




回答3:


The answer is no.

You can call free on that pointer to the last node, but that just means that the memory occupied by that node is no longer claimed. The data will most likely stay there unchanged for a while. And that means that the next-to-last node's pointer to it is still valid, even though it should not be.

To delete the node in a way that is meaningful to the list, that pointer contained in the next-to-last node has to be nullified. And that can't be done unless that next-to-last node can be accessed, either by a direct pointer to it, or by traversing the list from a preceding node.




回答4:


You can use a doubly linked list to access the previous node. Or iterate through the entire list.




回答5:


Yes you can.. Try the following code:

void deleteNode()
{
    mynode *temp1;
    for(temp1 = head; temp->next!= tail; temp1 = temp1->next);
    tail = temp1;
    free(tail->next);
}

It will delete the last node.



来源:https://stackoverflow.com/questions/9288237/can-we-delete-the-last-node-of-a-single-linked-list-if-we-only-know-the-address

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!