Principle: 1. If the node to be deleted is in the middle of a single-chain table, obtain the value of the next node of the node, copy it to the node to be deleted, and then delete the next node of the node to be deleted. 2. If the node to be deleted is at the end of the single-chain table, the single-chain table will be traversed sequentially and deleted. 3. If the linked list has only one node and it is the node to be deleted, delete it and modify the related pointer.
Core code:
// Delete the node at O (1) time. Note: You must ensure that pdel is the node void deletenode (list * List, pnode pdel) in the linked list {If (* List = NULL | pdel = NULL) {return ;} // If (pdel-> next! = NULL) {// copy the node value behind pdel and delete the node pnode ptemp = pdel-> next; pdel-> DATA = ptemp-> data; pdel-> next = ptemp-> next; free (ptemp); ptemp = NULL;} else if (* List = pdel) // The linked list has only one node {free (pdel); pdel = * List = NULL;} else // It is the last node {pnode ptemp = * List; while (ptemp-> next! = Pdel) {ptemp = ptemp-> next;} ptemp-> next = NULL; free (pdel); pdel = NULL ;}}
Complete code:
/* Delete the one-way linked list node in O (1) by rowandjj2014/7/25 */# include <iostream> using namespace STD; typedef struct _ node _ {int data; struct _ node _ * Next;} node, * pnode, * List; void addtotail (list * List, int data) {pnode pnew = (pnode) malloc (sizeof (node); If (! Pnew) {exit (-1) ;}pnew-> DATA = data; pnew-> next = NULL; If (* List = NULL) {* List = pnew ;} else {pnode ptemp = * List; while (ptemp-> next! = NULL) {ptemp = ptemp-> next;} ptemp-> next = pnew;} void create (list * List, int N) {If (n <= 0) {return;} int data; for (INT I = 0; I <n; I ++) {CIN> data; addtotail (list, data );}} pnode findnode (list, int data) {If (list = NULL) {return NULL;} pnode ptemp = List; while (ptemp! = NULL) {If (ptemp-> DATA = data) {return ptemp;} ptemp = ptemp-> next;} return NULL;} void traverse (list List) {pnode ptemp = List; while (ptemp! = NULL) {cout <ptemp-> data <"; ptemp = ptemp-> next;} cout <Endl ;}// in O (1) delete nodes at the specified time. Note: You must ensure that pdel is the node void deletenode (list * List, pnode pdel) in the linked list {If (* List = NULL | pdel = NULL) {return ;} // If (pdel-> next! = NULL) {// copy the node value behind pdel and delete the node pnode ptemp = pdel-> next; pdel-> DATA = ptemp-> data; pdel-> next = ptemp-> next; free (ptemp); ptemp = NULL;} else if (* List = pdel) // The linked list has only one node {free (pdel); pdel = * List = NULL;} else // It is the last node {pnode ptemp = * List; while (ptemp-> next! = Pdel) {ptemp = ptemp-> next;} ptemp-> next = NULL; free (pdel); pdel = NULL ;}} int main () {list = NULL; int N; CIN> N; Create (& list, n); traverse (list); int data; CIN> data; pnode P = findnode (list, data ); if (P! = NULL) {deletenode (& list, P);} traverse (list); Return 0 ;}