60. Delete the linked list node (linked list and algorithm) in O (1) time ).
Question: Given the head pointer and a node pointer of the linked list, delete the node at O (1) time. The linked list node is defined as follows:
Struct listnode
{
Int m_nkey;
Listnode * m_pnext;
};
The function declaration is as follows:
Void deletenode (listnode * plisthead, listnode * ptobedeleted );
Idea: copy the content of the next node of the current node to the current node and delete the next node. Note: Only one knots in the linked list cannot be deleted under the function declaration given by the question. To delete the last knots, You need to search from the beginning.
/* 60. Delete the linked list node (linked list and algorithm) in O (1) time ). Question: Given the head pointer and a node pointer of the linked list, delete the node at O (1) time. The linked list node is defined as follows: struct listnode {int m_nkey; listnode * m_pnext;}; function declaration: void deletenode (listnode * plisthead, listnode * ptobedeleted ); */# include <stdio. h> # include <stdlib. h> typedef struct listnode {int m_nkey; listnode * m_pnext;} listnode; void deletenode (listnode * plisthead, listnode * ptobedeleted) {If (ptobedeleted = NULL | plisthead = NULL) {return;} If (ptobedeleted-> m_pnext = NULL) // Delete the last node {Li Stnode * x = plisthead; If (ptobedeleted = plisthead) // there is only one node {printf ("can't delete the only note \ n ");} else {While (X-> m_pnext! = Ptobedeleted) // it is not acceptable to delete the last node cyclically and directly assign null values because a copy of the pointer is input {x = x-> m_pnext ;} x-> m_pnext = NULL; free (ptobedeleted);} return;} // copy data from the next node to the current node, actually Delete the next node listnode * TMP = primary-> m_pnext; ptobedeleted-> m_nkey = primary-> m_pnext-> m_nkey; ptobedeleted-> m_pnext = ptobedeleted-> m_pnext; free (TMP);} void printlist (listnode * plisthead) {listnode * x = plisthead; while (X! = NULL) {printf ("% d->", X-> m_nkey); X = x-> m_pnext;} printf ("\ n ");} void createlist (listnode * & plisthead) {int data; scanf ("% d", & data); If (Data! = 0) {plisthead = (listnode *) malloc (sizeof (listnode); plisthead-> m_nkey = data; plisthead-> m_pnext = NULL; createlist (plisthead-> m_pnext) ;}} int main () {listnode * P = NULL; createlist (p); printlist (p); deletenode (p, p-> m_pnext); printlist (p); Return 0 ;}