Data Structure-algorithm (027) (delete linked list nodes in O (1) Time)

Source: Internet
Author: User

[Statement: This article is only intended for self-Summary and mutual communication, and may be omitted. Email: Mr_chenping@163.com]

Question: Delete the linked list node in O (1) time and do not know the linked list Header

Question Analysis:

1. copy the data of the next node of the node to be deleted to the node to be deleted.

2. Delete the next node

Algorithm Implementation:

#include 
 
  #include 
  
   typedef struct _list_node{int        key;struct _list_node  *next;}list_node;void *list_insert(list_node *head, int key){list_node *p = head;while(p->next != NULL)p = p->next;list_node *node = calloc(1, sizeof(list_node));node->key = key;node->next = NULL;p->next = node;}void list_delete(list_node *del_node){list_node *p = del_node->next;del_node->key = p->key; /*copy data*/del_node->next = p->next;free(p);}void list_dispaly(list_node *head){list_node *p = head->next;printf("list:");while(p){printf(" %d", p->key);p = p->next;}printf("\n");}int main(int argc, char *argv[]){list_node *head = calloc(1, sizeof(list_node));head->key = 0;head->next = NULL;list_insert(head, 1);list_insert(head, 2);list_insert(head, 3);list_insert(head, 4);list_insert(head, 5);list_dispaly(head);list_delete(head->next->next);list_dispaly(head);return 0;}
  
 


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.