Ideas:
Time complexity requires O (1), known to delete the node, you can find the node's next node, the next node to copy the relevant information to the node to be deleted, delete the next node, you can achieve the topic requirements.
Note: When you delete a tail node, you need to traverse through it, and when you delete the head nodes, you need to move the head node to the next node.
#include <stdio.h> #include <stdlib.h> #include <assert.h>struct Listnode{int _value; listnode* _next;}; Void init (listnode*& head) {listnode* cur =head;if (cur==null) {cur= (Listnode*) malloc ( sizeof (ListNode)); cur->_next=null;cur->_value=0;} Head=cur;} Void push (listnode*& head,int value) {listnode* cur =head;while (cur->_next) {cur =cur->_next;} listnode* tmp=null;tmp= (listnode*) malloc (sizeof (ListNode)); tmp->_next=null;tmp->_value=value;cur- >_next=tmp;} Void pop (Listnode* head) {listnode* cur=head; Listnode* prev=null;while (cur->_next!=null) {prev=cur;cur=cur->_next;} Prev->_next=null;free (cur); cur=null;} Void print (listnode* head) {listnode* cur=head;while (cur) {printf ("%d\n", cur->_value); cur=cur- >_next;}} Listnode* find (Listnode* head,int value) {assert (head); Listnode* cur=head; while (cur) {if (cur->_value==Value) {return cur;} Else{cur=cur->_next;}}} Void deletenode (listnode* &head,listnode* ptobedeleted) {listnode* cur=head;if (cur== NULL) {return;} if (ptobedeleted==head) {head=cur->_next;free (cur); cur=null;return;} Listnode* last=ptobedeleted->_next;if (last!=null) {ptobedeleted->_value=last->_value; Ptobedeleted->_next=last->_next;free (last); last=null;} else //deleted is the tail node {listnode* prev=null;while (cur->_next!=null) {prev=cur;cur=cur- >_next;} Prev->_next=null;free (cur); cur=null;}} Void test () {listnode* head=null;init (head); push (head,1);p ush (head,2);p Ush ( head,3);/*pop (head); */print (head); Listnode* tmp=find (head,1);D Eletenode (head,head);p rint (head); Int main () {test (); System ("pause"); return 0;}
Results:
650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M01/7F/D4/wKioL1cvLKKiYkkGAAAWpJxGTE8537.png "style=" float: none; "Title=" 8CY) {91~xy6@s925wnvx[{5.png "alt=" Wkiol1cvlkkiykkgaaawpjxgte8537.png "/>
650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M01/7F/D6/wKiom1cvK8eC3aMXAAAbSjYwXrU914.png "style=" float: none; "title=" K@vtrruw2rx6jyrz$y03gde.png "alt=" Wkiom1cvk8ec3amxaaabsjywxru914.png "/>
This article from "Liveyoung" blog, reproduced please contact the author!
Delete a linked list node at O (1) time